Straight From the Raw Scores

Loss FunctionsMedium+20 XP+20

Straight From the Raw Scores

A classifier's last layer emits one raw score per class, the logits z1,…,zKz_1, \dots, z_Kz1​,…,zK​. Softmax turns them into probabilities, and categorical cross-entropy charges the model for the probability it gave the true class yyy:

pk=ezk∑jezj,L=−ln⁡pyp_k = \frac{e^{z_k}}{\sum_{j} e^{z_j}}, \qquad L = -\ln p_ypk​=∑j​ezj​ezk​​,L=−lnpy​

A batch's loss is the mean of its examples' losses.

Task: write mean_cross_entropy(logits, labels).

  • logits is a list of rows, one per example, each holding KKK logits.
  • labels holds each example's true class index, counting from 0.
  • Return the batch's mean loss, rounded to 4 decimal places.

Real logits are not tidy. Yours may be anywhere between −1000-1000−1000 and 100010001000. A model that is confidently wrong can give the true class a probability far too small for a computer to store, so it comes out as exactly 0.0. The true loss for that example is still an ordinary finite number (it can run into the hundreds), and your function must return its exact value: no crash, no inf, and no capping it at something smaller.

When a training loss suddenly turns into NaN, this calculation is one of the first places to look: an eze^{z}ez that overflowed, or a ln⁡0\ln 0ln0.

Cross-Entropy Loss in Training

Logit z_1:1.0
Logit z_2:0.2
Logit z_3:-1.0
True Label:

Softmax Probabilities

Prob(Class 1): 63.1% (True Label)
Prob(Class 2): 28.4%
Prob(Class 3): 8.5%

Loss Output

Cross-Entropy: 0.4604 nats

The loss is simply −ln(p) for the true label. Minimising it forces the network to assign higher probability to the correct label.

Examples

logits = [[2.0, 0.5, -1.0]]
labels = [0]
returns 0.2413
logits = [[0.2, 1.7], [3.0, -0.4], [1.1, 1.1]]
labels = [1, 0, 0]
returns 0.3091

Hints

Solve it to unlock the solution

Once your code passes every test, a reference solution shows up here so you can compare it with yours.

solution.py
CtrlEnterto run