Cross-Entropy Loss: Only the Correct Class Counts

Loss FunctionsMedium+20 XP+15

Cross-Entropy Loss: Only the Correct Class Counts

Cross-entropy scores a predicted probability distribution against the truth. Because the true label is one-hot, almost every term drops out and the loss for one sample collapses to a single number: the negative log of the probability you gave the correct class.

1loss = -(1/n) * Σ log(p[correct class])

Task: write cross_entropy(predictions, targets) where predictions[i] is a probability distribution over classes and targets[i] is the index of the correct class. Return the mean loss, rounded to 4 decimal places.

  • Natural log, not log base 2.
  • Every probability in the test cases is strictly positive, so no clipping is required.

The curve is deliberately lopsided. Predicting 0.9 for the right answer costs almost nothing, while predicting 0.01 costs a great deal — the loss punishes confident mistakes far harder than it rewards confident hits, which is what keeps a model from bluffing.

cat60%
dog20%
bird15%
fish5%
loss (truth = cat)0.51

Only the probability given to the true class matters.

Examples

predictions = [[0.7, 0.2, 0.1], [0.1, 0.8, 0.1]]
targets = [0, 1]
returns 0.2899
predictions = [[0.25, 0.25, 0.25, 0.25]]
targets = [2]
returns 1.3863

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