Compute class-weighted cross-entropy

MediumLosses

Why it matters Safety classifiers with rare positive classes are trained with weighted cross-entropy.

When one class is rare, weighting the loss by class makes mistakes on it cost more.

Write weighted_ce(logits, y, w). logits is (n, k), y is (n,), w is (k,) class weights. Per-sample loss is w[y_i] * (-log softmax(logits_i)[y_i]). Return the weighted mean: sum of per-sample losses divided by sum of w[y_i].

Signaturedef weighted_ce(logits, y, w)

Example

logits [[0, 0]], y [1], w [1, 3] gives log 2 = 0.6931.

Understand the idea

If 95 percent of samples are class 0, a model can ignore class 1 and still look good. Class-weighted cross-entropy multiplies each sample's loss by a weight for its true class, so mistakes on rare classes cost more. Dividing by the total weight keeps the loss on a stable scale. Worked example: logits [[0, 0], [2, 0]], y = [1, 0], w = [1, 3]. Sample 1 has true class 1 with weight 3; its softmax probability is 0.5, so its loss is 3 * log 2 = 2.079. Sample 2 has true class 0 with weight 1; its loss is log(1 + e^-2) = 0.127. Total = 2.206, total weight = 3 + 1 = 4, so the result is about 0.552. Rule: loss_i = w[y_i] * (-log softmax(logits_i)[y_i]); return sum(loss_i) / sum(w[y_i]). Compute log softmax stably by subtracting each row's max. Dividing by n instead of the weight sum changes the scale whenever weights are not all 1. Used in: imbalanced classification such as fraud or toxicity detection, and it matches the weighted mean option in PyTorch cross-entropy.

solution.pyPython idle
Ctrl/Cmd + Enter runs sample tests

Run checks the first 2 tests. Submit checks all 3.

  • Sample 1: exampleweighted_ce([[0, 0]], [1], [1, 3])
  • Sample 2: imbalancedweighted_ce([[2, 0], [0, 1], [1, 1]], [0, 1, 1], [1, 5])
  • Test 3: randomweighted_ce(_Z, _y, [0.5, 2.0, 1.0])