WRITE · TRACE · UNDERSTAND

Weight stable multiclass cross-entropy by observations

Return the weighted mean multiclass negative log likelihood.

Read lesson: Weight stable multiclass cross-entropy by observations →

Your experiment

Return the weighted mean multiclass negative log likelihood. Subtract each row maximum before exponentiation. Require aligned nonempty batches, rectangular logits with at least two classes, finite values, integer class indices, nonnegative finite weights and a positive total weight. The denominator is total observation weight, not batch length.

Python runs in your browser. Your draft stays on this device.

What to look for

Compare shifted and unshifted logits, duplicated weighted observations and a confidently wrong class. Review label identities and the weight denominator before optimizing the kernel.

Watch your code work

Ready to experiment

Write a solution or load the worked answer, then choose Trace & check.

Step through arrays, variables and training curves produced by your own Python.

About this algorithm

How Weight stable multiclass cross-entropy by observations works

The idea

Multiclass cross-entropy is the negative log of the probability a model gives to the correct class. With raw scores, called logits, that probability comes from a softmax, so the loss for one row is log(sum(exp(logits))) - logits[target]. Computed literally, exp(1000) overflows. The fix is to subtract the row maximum before exponentiating and add it back afterwards. The largest term becomes exp(0), which is 1, and the answer is unchanged because a softmax ignores a constant shift.

multiclass_loss then averages the row losses with observation weights. The denominator is sum(weights), not the number of rows, so a row with weight 2 counts like two identical rows and a row with weight 0 drops out.

How it works

  1. Validate the batch: aligned nonempty inputs, rectangular logits with at least two classes, finite values, integer class indices, and nonnegative weights with a positive total.
  2. For each row, take maximum = max(row).
  3. Compute normalizer = log(sum(exp(x - maximum))), where no exponent is above zero.
  4. Form the row loss as normalizer + maximum - row[target].
  5. Multiply each loss by its weight, add them up, and divide by the sum of the weights.

What it costs

Time
O(n·c)
Space
O(n)

Every row reads its c logits a constant number of times, and one loss per row is kept until the weighted mean.

Where it is used

  • PyTorch's cross_entropy takes raw logits and applies a log-softmax internally for the same numerical reason.
  • scipy.special.logsumexp implements this trick of subtracting the maximum before exponentiating.
  • scikit-learn's log_loss accepts sample_weight and returns the weighted average over samples.

Watch out for

  • Calling math.exp on raw logits: exp(1000) raises OverflowError even though the correct loss is about 0.31.
  • Dividing the weighted sum by len(labels), which changes the result whenever the weights do not add up to the batch size.
  • Accepting True as a class index because bool is a subclass of int; the Lab checks type(y) is int.