Return classification accuracy of input
2058
def _value_function(self, x_input, y_true, y_pred):
        
        if len(y_true.shape) == 1:
            return y_pred.argmax(1).eq(y_true).double().mean().item()
        else:
            raise NotImplementedError
605228
def roc_auc_cv(self,features,labels):
        """"""        
        if callable(getattr(self.ml, "decision_function", None)):
            return np.mean([self.scoring_function(labels[test],
                            self.pipeline.fit(features[train],labels[train]).
                                         decision_function(features[test]))
                            for train, test in KFold().split(features, labels)])
        elif callable(getattr(self.ml, "predict_proba", None)):
            return np.mean([self.scoring_function(labels[test],
                            self.pipeline.fit(features[train],labels[train]).
                                            predict_proba(features[test])[:,1])
                            for train, test in KFold().split(features, labels)]) 
        else:
            raise ValueError("ROC AUC score won't work with " + self.ml_type + ". No "
                    "decision_function or predict_proba method found for this learner.")
1298015
def padded_accuracy(logits, labels):
  """"""
  with tf.variable_scope("padded_accuracy", values=[logits, labels]):
    logits, labels = _pad_tensors_to_same_length(logits, labels)
    weights = tf.to_float(tf.not_equal(labels, 0))
    outputs = tf.to_int32(tf.argmax(logits, axis=-1))
    padded_labels = tf.to_int32(labels)
    return tf.to_float(tf.equal(outputs, padded_labels)), weights
698549
def auc_roc_score(input:Tensor, targ:Tensor):
    ""
    fpr, tpr = roc_curve(input, targ)
    d = fpr[1:] - fpr[:-1]
    sl1, sl2 = [slice(None)], [slice(None)]
    sl1[-1], sl2[-1] = slice(1, None), slice(None, -1)
    return (d * (tpr[tuple(sl1)] + tpr[tuple(sl2)]) / 2.).sum(-1)
1111378
def rounding_accuracy(predictions,
                      labels,
                      weights_fn=common_layers.weights_nonzero):
  """"""
  outputs = tf.squeeze(tf.to_int32(predictions))
  labels = tf.squeeze(labels)
  weights = weights_fn(labels)
  labels = tf.to_int32(labels)
  return tf.to_float(tf.equal(outputs, labels)), weights
657367
def padded_sequence_accuracy(predictions,
                             labels,
                             weights_fn=common_layers.weights_nonzero):
  """"""
  # If the last dimension is 1 then we're using L1/L2 loss.
  if common_layers.shape_list(predictions)[-1] == 1:
    return rounding_sequence_accuracy(
        predictions, labels, weights_fn=weights_fn)
  with tf.variable_scope(
      "padded_sequence_accuracy", values=[predictions, labels]):
    padded_predictions, padded_labels = common_layers.pad_with_zeros(
        predictions, labels)
    weights = weights_fn(padded_labels)

    # Flatten, keeping batch dim (and num_classes dim for predictions)
    # TPU argmax can only deal with a limited number of dimensions
    predictions_shape = common_layers.shape_list(padded_predictions)
    batch_size = predictions_shape[0]
    num_classes = predictions_shape[-1]
    flat_size = common_layers.list_product(
        common_layers.shape_list(padded_labels)[1:])
    padded_predictions = tf.reshape(
        padded_predictions,
        [batch_size, common_layers.list_product(predictions_shape[1:-1]),
         num_classes])
    padded_labels = tf.reshape(padded_labels, [batch_size, flat_size])
    weights = tf.reshape(weights, [batch_size, flat_size])

    outputs = tf.to_int32(tf.argmax(padded_predictions, axis=-1))
    padded_labels = tf.to_int32(padded_labels)
    not_correct = tf.to_float(tf.not_equal(outputs, padded_labels)) * weights
    axis = list(range(1, len(outputs.get_shape())))
    correct_seq = 1.0 - tf.minimum(1.0, tf.reduce_sum(not_correct, axis=axis))
    return correct_seq, tf.constant(1.0)
1045397
def neural_net_predict(params, inputs):
    """"""
    inpW, inpb = params[0]
    inputs = relu(np.dot(inputs, inpW) + inpb)
    for W, b in params[1:-1]:
        outputs = batch_normalize(np.dot(inputs, W) + b)
        inputs = relu(outputs)
    outW, outb = params[-1]
    outputs = np.dot(inputs, outW) + outb
    return outputs
1497
def neural_net_predict(params, inputs):
    """"""
    for W, b in params:
        outputs = np.dot(inputs, W) + b
        inputs = np.tanh(outputs)
    return outputs - logsumexp(outputs, axis=1, keepdims=True)
1134727
def cross_entropy_error(self, input_data, targets, average=True,
                            cache=None, prediction=False):
        

        if cache is not None:
            activations = cache
        else:
            activations = \
              self.feed_forward(input_data, prediction=prediction)

        loss = cross_entropy_logistic(activations, targets)

        if average: loss /= targets.shape[0]
        # assert np.isfinite(loss)
        return loss.get()
1351645
def infer(self, input_data, input_label):
        
        sum_losses = 0
        len_losses = 0
        for data, label in zip(input_data, input_label):
            pred = self.net(data)
            sum_losses += mx.nd.array(self.loss_fn(pred, label)).sum().asscalar()
            len_losses += len(data)
            pred_convert = char_beam_search(pred)
            label_convert = char_conv(label.asnumpy())
            for target, pred in zip(label_convert, pred_convert):
                print("target:{t}  pred:{p}".format(t=target, p=pred))
        return sum_losses, len_losses
27737
def rounding_sequence_accuracy(predictions,
                               labels,
                               weights_fn=common_layers.weights_nonzero):
  """"""
  outputs = tf.squeeze(tf.to_int32(predictions), axis=-1)
  weights = weights_fn(labels)
  labels = tf.to_int32(labels)
  not_correct = tf.to_float(tf.not_equal(outputs, labels)) * weights
  axis = list(range(1, len(outputs.get_shape())))
  correct_seq = 1.0 - tf.minimum(1.0, tf.reduce_sum(not_correct, axis=axis))
  return correct_seq, tf.constant(1.0)
1185925
def predict(inputs_list, problem, request_fn):
  """"""
  assert isinstance(inputs_list, list)
  fname = "inputs" if problem.has_inputs else "targets"
  input_encoder = problem.feature_info[fname].encoder
  input_ids_list = [
      _encode(inputs, input_encoder, add_eos=problem.has_inputs)
      for inputs in inputs_list
  ]
  examples = [_make_example(input_ids, problem, fname)
              for input_ids in input_ids_list]
  predictions = request_fn(examples)
  output_decoder = problem.feature_info["targets"].encoder
  outputs = [
      (_decode(prediction["outputs"], output_decoder),
       prediction["scores"])
      for prediction in predictions
  ]
  return outputs
561736
def get_data_classif(dataset, n, nz=.5, theta=0, random_state=None, **kwargs):
    
    return make_data_classif(dataset, n, nz=.5, theta=0, random_state=None, **kwargs)
240844
def get_data(n_samples=100):
    """"""
    X, y = make_classification(
        n_samples=n_samples,
        n_features=N_FEATURES,
        n_classes=N_CLASSES,
        random_state=0,
    )
    X = X.astype(np.float32)
    return X, y
810253
def accuracy(y, z):
    
    tp, tn, fp, fn = contingency_table(y, z)
    return (tp + tn) / (tp + tn + fp + fn)
730573
function predict(face) {
      const inputDescriptor = getNet().computeFaceDescriptor(face)
      return getDescriptorsByClass().map(ds => ({
        className: ds.className,
        distance: computeMeanDistance(ds.faceDescriptors, inputDescriptor)
      }))
    }
768190
def get_correctness_for_response(self, response):
        """"""
        for answer in self.my_osid_object.get_answers():
            if self._is_match(response, answer):
                try:
                    return answer.get_score()
                except AttributeError:
                    return 100
        for answer in self.my_osid_object.get_wrong_answers():
            if self._is_match(response, answer):
                try:
                    return answer.get_score()
                except AttributeError:
                    return 0
        return 0