A workaround for 'use_bias' attribute since onnx don't provide this attribute,
        we have to check the number of inputs to decide it.
517916
def _fix_bias(self, op, attrs, num_inputs):
        """"""
        if op not in [mx.sym.Convolution, mx.sym.Deconvolution, mx.sym.FullyConnected]:
            return attrs
        if num_inputs == 3:
            attrs['no_bias'] = False
        elif num_inputs == 2:
            attrs['no_bias'] = True
        else:
            raise ValueError("Unexpected number of inputs for: {}".format(op))
        return attrs
157961
def convert_batchnorm(builder, layer, input_names, output_names, keras_layer):
    

    # Get input and output names
    input_name, output_name = (input_names[0], output_names[0])

    # Currently CoreML supports only per-channel batch-norm
    if keras_layer.mode != 0:
        raise NotImplementedError(
            'Currently supports only per-feature normalization')

    axis = keras_layer.axis
    nb_channels = keras_layer.input_shape[axis]


    # Set parameters
    # Parameter arrangement in Keras: gamma, beta, mean, variance
    gamma = keras_layer.get_weights()[0]
    beta = keras_layer.get_weights()[1]
    mean = keras_layer.get_weights()[2]
    std = keras_layer.get_weights()[3]
    # compute adjusted parameters
    variance = std * std
    f = 1.0 / np.sqrt(std + keras_layer.epsilon)
    gamma1 = gamma*f
    beta1 = beta - gamma*mean*f
    mean[:] = 0.0 #mean
    variance[:] = 1.0 - .00001 #stddev

    builder.add_batchnorm(
        name = layer,
        channels = nb_channels,
        gamma = gamma1,
        beta = beta1,
        mean = mean,
        variance = variance,
        input_name = input_name,
        output_name = output_name)
628794
function calcCFFSubroutineBias(subrs) {
            var bias;
            if (subrs.length < 1240) {
                bias = 107;
            }
            else if (subrs.length < 33900) {
                bias = 1131;
            }
            else {
                bias = 32768;
            }

            return bias;
        }
1128622
def _raise_error_if_not_sarray(dataset, variable_name="SArray"):
    
    err_msg = "Input %s is not an SArray."
    if not isinstance(dataset, _SArray):
      raise ToolkitError(err_msg % variable_name)
1215787
def check_input_stream_count(expected_number_of_streams):
    

    def stream_count_decorator(func):
        def func_wrapper(*args, **kwargs):
            self = args[0]
            sources = kwargs['sources'] if 'sources' in kwargs else args[1]
            if expected_number_of_streams == 0:
                if sources:
                    raise ValueError("No input streams expected")
            else:
                given_number_of_streams = len(sources) if sources else 0
                if given_number_of_streams != expected_number_of_streams:
                    raise ValueError("{} tool takes {} stream(s) as input ({} given)".format(
                        self.__class__.__name__, expected_number_of_streams, given_number_of_streams))
            return func(*args, **kwargs)

        return func_wrapper

    return stream_count_decorator
1367062
def sg_rnn_layer_func(func):
    
    """
    @wraps(func)
    def wrapper(tensor, **kwargs):
        r"""Manages arguments of `tf.sg_opt`.

        Args:
          tensor: automatically passed by decorator
          kwargs:
              in_dim: An integer. The size of input dimension, which is set to the last one by default.
              dim: An integer. The size of output dimension. Has the same value as in_dim by default.
              ln: Boolean. If True, layer normalization is applied.
              bias: Boolean. If True, biases are added. As a default, it is set to True
              name: A name for the layer. As a default, the function name is assigned.
              reuse: `True` or `None`; if `True`, we go into reuse mode for this `layer` scope
                as well as all sub-scopes; if `None`, we just inherit the parent scope reuse.
              summary: If True, summaries are added. The default is True.
        """

        # kwargs parsing
        opt = tf.sg_opt(kwargs) + sg_get_context()

        # set default argument
        try:
            shape = tensor.get_shape().as_list()
            # dropout off
            opt += tf.sg_opt(shape=shape, in_dim=shape[-1], dim=shape[-1], dout=0, summary=True)
            # disable bias when normalization on
            opt += tf.sg_opt(bias=not opt.ln)
        finally:
            pass

        # automatic layer naming
        if opt.name is None:

            # layer function name will be used as layer name
            opt.name = func.__name__.replace('sg_', '')

            # find existing layer names
            exist_layers = []
            for t in tf.global_variables():
                scope_name = tf.get_variable_scope().name
                prefix = scope_name + '/' if len(scope_name) > 0 else ''
                i = t.name.rfind(prefix + opt.name)
                if i >= 0:
                    exist_layers.append(t.name[i:].split('/')[-2])
            exist_layers = list(set(exist_layers))

            # layer name numbering
            if len(exist_layers) == 0:
                opt.name += '_1'
            else:
                opt.name += '_%d' % (max([int(n.split('_')[-1]) for n in exist_layers]) + 1)

        with tf.variable_scope(opt.name, reuse=opt.reuse) as scope:

            # call layer function
            out = func(tensor, opt)

            # apply dropout
            if opt.dout:
                out = tf.cond(_phase,
                              lambda: tf.nn.dropout(out, 1 - opt.dout),
                              lambda: out)

            # rename tensor
            out = tf.identity(out, 'out')

            # add final output summary
            if opt.summary:
                tf.sg_summary_activation(out)

            # save node info for reuse
            out._sugar = tf.sg_opt(func=func, arg=tf.sg_opt(kwargs) + sg_get_context(),
                                   prev=tensor, is_layer=True, name=opt.name)
            # inject reuse function
            out.sg_reuse = types.MethodType(sg_reuse, out)

        return out

    return wrapper
716843
def get_error(data, labels, pos_neurons, neg_neurons = [], add_noise = True):
  
  num_correct = 0
  num_false_positives = 0
  num_false_negatives = 0
  classifications = numpy.zeros(data.nRows())
  for neuron in pos_neurons:
    classifications += neuron.calculate_on_entire_dataset(data)
  for neuron in neg_neurons:
    classifications -= neuron.calculate_on_entire_dataset(data)
  if add_noise:
    classifications += (numpy.random.rand() - 0.5)/1000
  classifications = numpy.sign(classifications)
  for classification, label in zip(classifications, labels):
    if classification > 0 and label > 0:
      num_correct += 1.0
    elif classification <= 0 and label <= 0:
      num_correct += 1.0
    elif classification > 0 and label <= 0:
      num_false_positives += 1
    else:
      num_false_negatives += 1
  return (1.*num_false_positives + num_false_negatives)/data.nRows(), num_false_positives, num_false_negatives
343922
def bninception(num_classes=1000, pretrained='imagenet'):
    
    """
    model = BNInception(num_classes=num_classes)
    if pretrained is not None:
        settings = pretrained_settings['bninception'][pretrained]
        assert num_classes == settings['num_classes'], \
            "num_classes should be {}, but is {}".format(settings['num_classes'], num_classes)
        model.load_state_dict(model_zoo.load_url(settings['url']))
        model.input_space = settings['input_space']
        model.input_size = settings['input_size']
        model.input_range = settings['input_range']
        model.mean = settings['mean']
        model.std = settings['std']
    return model
178525
def amean(x, weights=None):
    
    w_arr, x_arr = _preprocess_inputs(x, weights)
    return (w_arr*x_arr).sum(axis=0) / w_arr.sum(axis=0)
439948
def __get_inferred_data_res_2(v=None, calc=True):
    
    # Base: If something goes wrong, or if there are no values, then use "NaN" placeholders.
    d = {
        "hasMinValue": "nan", "hasMaxValue": "nan",
        "hasMeanValue": "nan", "hasMedianValue": "nan",
    }
    try:
        if calc:
            _min = np.nanmin(v)
            _max = np.nanmax(v)
            _mean = np.nanmean(v)
            _med = np.nanmedian(v)

            if np.isnan(_min):
                _min = "nan"
            else:
                _min = abs(_min)
            if np.isnan(_max):
                _max = "nan"
            else:
                _min = abs(_min)
            if np.isnan(_mean):
                _mean = "nan"
            else:
                _min = abs(_min)
            if np.isnan(_med):
                _med = "nan"
            else:
                _min = abs(_min)

            d = {
                "hasMinValue": _min,
                "hasMaxValue": _max,
                "hasMeanValue": _mean,
                "hasMedianValue": _med
            }
    except Exception as e:
        logger_inferred_data.error("get_inferred_data_res_2: {}".format(e))

    return d
599046
def ma_bias_ratio_pivot(self, data, sample_size=5, position=False):
        """"""
        sample = data[-sample_size:]

        if position is True:
            check_value = max(sample)
            pre_check_value = max(sample) > 0
        elif position is False:
            check_value = min(sample)
            pre_check_value = max(sample) < 0

        return ((sample_size - sample.index(check_value) < 4 and
                 sample.index(check_value) != sample_size - 1 and pre_check_value),
                sample_size - sample.index(check_value) - 1,
                check_value)
90036
def optimize_onnx_model(origin_model, nchw_inputs=None):
    
    graph = origin_model.graph
    nodelist = list(graph.node)
    del graph.node[:]

    all_nodes = optimize_onnx(nodelist,
                              inputs=graph.input,
                              outputs=graph.output)
    nodes = [n_ for n_ in all_nodes if not isinstance(n_, tuple)]
    graph.node.extend(nodes)

    alter_tensors = {n_[1]: n_[0] for n_ in all_nodes if isinstance(n_, tuple)}
    update_tensor = lambda x: \
        helper.make_tensor(x.name, x.data_type, (x.dims[0], 1, 1),
                           onnx.numpy_helper.to_array(x).flatten())
    new_initializer = [init_ if init_.name not in alter_tensors else update_tensor(init_)
                       for init_ in graph.initializer]
    del graph.initializer[:]
    graph.initializer.extend(new_initializer)

    update_value_info = lambda x: \
        helper.make_tensor_value_info(x.name, x.type.tensor_type.elem_type,
                                      (x.type.tensor_type.shape.dim[0].dim_value, 1, 1))
    new_input = [in_ if in_.name not in alter_tensors else update_value_info(in_)
                 for in_ in graph.input]
    del graph.input[:]
    graph.input.extend(new_input)
    return origin_model
1185168
def std_check_in(dataset, name, allowed_vals):
    
    if not hasattr(dataset, name):
        return 0

    ret_val = 1
    if getattr(dataset, name) in allowed_vals:
        ret_val += 1

    return ret_val
988934
def pc_bias(s, o):
    
    # s,o = filter_nan(s,o)
    return 100.0*np.sum(s-o)/np.sum(o)
1371416
def prepare_input_data(self, X):
        
        X = check_array(X, force_all_finite=False)
        if X.dtype != "f" and X.dtype != "d":
            X = X.astype(float)

        self._check_input(X)
        missing_mask = np.isnan(X)
        self._check_missing_value_mask(missing_mask)
        return X, missing_mask
1209334
def weights_multi_problem_input(labels, taskid=-1):
  """"""
  taskid = check_nonnegative(taskid)
  weights_all_tokens = weights_multi_problem_all(labels, taskid)
  weights_target = weights_multi_problem(labels, taskid)
  return weights_all_tokens - weights_target
727401
function Bias(average, rowBiases, colBiases) {
	this.average = average;		// Overall value average
	this.rowBiases = rowBiases; // Bias for each row
	this.colBiases = colBiases;	// Bias for each column
}