On an imbalanced dataset the plain cross-entropy is dominated by the majority class. Reweight each example by its class so that every class contributes equally, then compute the weighted loss and its gradient with respect to the logits.
Implement class_weighted_cross_entropy(y, logits, class_weight="balanced") and return (loss, grad, weights).
y: length- integer labels.logits: either a length- 1-D array (binary case: the model predicts , labels are 0/1) or an array (multi-class case: probabilities are the softmax of each row, labels are in ).class_weight: "balanced", None (every weight 1.0) or a dict mapping each label to its weight.Balanced weights use only the classes present in y. With distinct labels and examples of class ,
With and the usual per-example cross-entropy ( of the probability given to the true class), the loss is the weighted mean
and grad is with the same shape as logits.
Return loss as a float, grad as a list (nested for 2-D) and weights as a dict {label: weight} over the labels present in y.
log(0).