Loss for class label.
435021
def sigmoid_class_label_loss(top_out,
                             targets,
                             model_hparams,
                             vocab_size,
                             weights_fn):
  """"""
  # Expect inputs of size [batch-size, timesteps, 1, num-classes], where the
  # last dimension of num-classes represents logits for binary labels
  del model_hparams, vocab_size  # unused arg
  loss_scale = tf.losses.sigmoid_cross_entropy(
      multi_class_labels=targets, logits=top_out)
  weights = weights_fn(targets)
  loss_denom = tf.reduce_sum(weights)
  return loss_scale, loss_denom
1374236
function LDA(...classes) {
	// Compute pairwise LDA classes (needed for multiclass LDA)
	if(classes.length < 2) {
		throw new Error('Please pass at least 2 classes');
	}

	let numberOfPairs = classes.length * (classes.length - 1) / 2;
	let pair1 = 0;
	let pair2 = 1;

	let pairs = new Array(numberOfPairs);

	for(let i = 0; i < numberOfPairs; i++){
		pairs[i] = computeLdaParams(classes[pair1], classes[pair2], pair1, pair2);

		pair2++;
		if(pair2 == classes.length) {
			pair1++;
			pair2 = pair1 + 1;
		}
	} 

	this.pairs = pairs;
	this.numberOfClasses = classes.length;
}
1361290
def padded_neg_log_perplexity(logits, labels, vocab_size):
  """"""
  num, den = padded_cross_entropy_loss(logits, labels, 0, vocab_size)
  return -num, den
1266214
def process_or_validate_classifier_output_features(
        output_features, class_labels, supports_class_scores = True):

    

    def raise_error(msg):

        raise ValueError("Classifier error: %s" % msg)

    class_labels = list(class_labels)

    # First, we need to determine the type of the classes.
    _int_types = _integer_types + (bool, _np.bool_, _np.int32, _np.int64)

    if all(isinstance(cl, _int_types) for cl in class_labels):
        output_class_type = datatypes.Int64()

    elif all(isinstance(cl, _string_types) for cl in class_labels):
        output_class_type = datatypes.String()

    else:
        raise ValueError('Class labels must be all of type int or all of type string.')

    if output_features is None:

        out = [("classLabel", output_class_type)]

        if supports_class_scores:
            out += [("classProbability", datatypes.Dictionary(output_class_type))]

    elif isinstance(output_features, _string_types):

        out = [(output_features, output_class_type)]

        if supports_class_scores:
            out += [("classProbability", datatypes.Dictionary(output_class_type))]

    elif (isinstance(output_features, (list, tuple))
            and all(isinstance(fn, _string_types) for fn in output_features)
            and len(output_features) == 2):

        if supports_class_scores:
            out = [(output_features[0], output_class_type),
                   (output_features[1], datatypes.Dictionary(output_class_type))]
        else:
            raise ValueError("Classifier model (as trained) does not support output scores for classes.")

    elif is_valid_feature_list(output_features):

        output_features = [(k, datatypes._normalize_datatype(dt)) for k, dt in output_features]

        if len(output_features) == 1 or not supports_class_scores:
            if not output_features[0][1] == output_class_type:
                raise ValueError("Type of output class feature does not match type of class labels.")

        else:
            # Make sure the first two output features specified give the output
            # class field and the output class scores dictionary field
            if (isinstance(output_features[0][1], datatypes.Dictionary)
                    and isinstance(output_features[1][1], output_class_type)):

                output_features[0], output_features[1] = output_features[1], output_features[0]

            if not isinstance(output_features[1][1], datatypes.Dictionary):
                raise_error("Output features class scores should be dictionary type.")

            if output_features[1][1].key_type != output_class_type:
                raise_error("Class scores dictionary key type does not match type of class labels.")

            if output_features[0][1] != output_class_type:
                raise_error("Specified type of output class does not match type of class labels.")

        # NOTE: We are intentionally allowing the case where additional fields are allowed
        # beyond the original two features.

        out = output_features

    else:
        raise_error("Form of output features not recognized")

    return out
296037
def ccmodmsk_class_label_lookup(label):
    """"""

    clsmod = {'ism': admm_ccmod.ConvCnstrMODMaskDcpl_IterSM,
              'cg': admm_ccmod.ConvCnstrMODMaskDcpl_CG,
              'cns': admm_ccmod.ConvCnstrMODMaskDcpl_Consensus,
              'fista': fista_ccmod.ConvCnstrMODMask}
    if label in clsmod:
        return clsmod[label]
    else:
        raise ValueError('Unknown ConvCnstrMODMask solver method %s' % label)
1044506
def labels(self, include_missing=False, include_transforms_for_dims=False):
        
        return [
            dim.labels(include_missing, include_transforms_for_dims)
            for dim in self.dimensions
        ]
121221
def get_loss(self, pred: mx.sym.Symbol, labels: mx.sym.Symbol) -> mx.sym.Symbol:
        
        labels = mx.sym.reshape(labels, shape=(-1, 1))
        loss_value = self.loss_config.length_task_weight / 2 * mx.sym.square(pred - labels)
        loss_value = mx.sym.MakeLoss(data=loss_value,
                                     normalization='batch',
                                     name=self.name)
        return loss_value
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
465606
def loss(logits, labels):
  
  labels = tf.to_int64(labels)
  cross_entropy = tf.nn.sparse_softmax_cross_entropy_with_logits(
      logits=logits, labels=labels, name='xentropy')
  return tf.reduce_mean(cross_entropy, name='xentropy_mean')
340824
def label(self):
        ''''''
        if self.__doc__ and self.__doc__.strip():
            return self.__doc__.strip().splitlines()[0]
        return humanize(self.__class__.__name__)
1183373
def error_rate(predictions, labels):
  """"""
  return 100.0 - (
      100.0 *
      np.sum(np.argmax(predictions, 1) == np.argmax(labels, 1)) /
      predictions.shape[0])
673475
def get_loss(config: LossConfig) -> 'Loss':
    
    if config.name == C.CROSS_ENTROPY:
        return CrossEntropyLoss(config,
                                output_names=[C.SOFTMAX_OUTPUT_NAME],
                                label_names=[C.TARGET_LABEL_NAME])
    else:
        raise ValueError("unknown loss name: %s" % config.name)
1185696
@Override
  public void buildClassifier(Database database, Relation<? extends ClassLabel> labelrep) {
    Object2IntOpenHashMap<ClassLabel> count = new Object2IntOpenHashMap<>();
    for(DBIDIter iter = labelrep.iterDBIDs(); iter.valid(); iter.advance()) {
      count.addTo(labelrep.get(iter), 1);
    }
    int max = Integer.MIN_VALUE;
    double size = labelrep.size();

    distribution = new double[count.size()];
    labels = new ArrayList<>(count.size());
    ObjectIterator<Entry<ClassLabel>> iter = count.object2IntEntrySet().fastIterator();
    for(int i = 0; iter.hasNext(); ++i) {
      Entry<ClassLabel> entry = iter.next();
      distribution[i] = entry.getIntValue() / size;
      labels.add(entry.getKey());
      if(entry.getIntValue() > max) {
        max = entry.getIntValue();
        prediction = entry.getKey();
      }
    }
  }
1007238
def _log_loss(y, y_pred, w):
    """"""
    eps = 1e-15
    inv_y_pred = np.clip(1 - y_pred, eps, 1 - eps)
    y_pred = np.clip(y_pred, eps, 1 - eps)
    score = y * np.log(y_pred) + (1 - y) * np.log(inv_y_pred)
    return np.average(-score, weights=w)
872245
def dense_to_one_hot(labels_dense, num_classes):
        """"""
        num_labels = labels_dense.shape[0]
        index_offset = np.arange(num_labels) * num_classes
        labels_one_hot = np.zeros((num_labels, num_classes))
        labels_one_hot.flat[index_offset + labels_dense.ravel()] = 1
        return labels_one_hot
616655
def get_loss(self, logits: mx.sym.Symbol, labels: mx.sym.Symbol) -> mx.sym.Symbol:
        
        if self.loss_config.normalization_type == C.LOSS_NORM_VALID:
            normalization = "valid"
        elif self.loss_config.normalization_type == C.LOSS_NORM_BATCH:
            normalization = "null"
        else:
            raise ValueError("Unknown loss normalization type: %s" % self.loss_config.normalization_type)
        return mx.sym.SoftmaxOutput(data=logits,
                                    label=labels,
                                    ignore_label=self.ignore_label,
                                    use_ignore=True,
                                    normalization=normalization,
                                    smooth_alpha=self.loss_config.label_smoothing,
                                    name=self.name)
1189232
def DiscriminatorLayerLoss():
    '''
    '''

    data = mx.sym.Variable('data')

    label = mx.sym.Variable('label')

    data = mx.sym.Flatten(data)
    label = mx.sym.Flatten(label)

    label = mx.sym.BlockGrad(label)

    zeros = mx.sym.zeros_like(data)

    output = -GaussianLogDensity(label, data, zeros)

    dloss = mx.symbol.MakeLoss(mx.symbol.mean(output),name='lloss')

    return dloss