Week 11 · Entropy, cross-entropy, and stable softmax

Measure the cost of a probability forecast and compute the loss without overflowing on large scores.

Watch on YouTube

Subject contents · Week 10 · Week 12

Measure the cost of a probability forecast and compute the loss without overflowing on large scores.

Score a forecast by the probability it gave the outcome

Imagine a classifier predicting which of three categories an example belongs to. Two models can both predict the correct category while assigning it very different probabilities. A probability of 0.51 expresses much less confidence than 0.99. Log loss gives those two forecasts different scores. If a model is very confident in the wrong class, the loss makes that mistake visible.

This lesson connects the loss on one outcome to entropy across many possible outcomes. It then shows how to calculate the same loss when a classifier outputs raw scores large enough to cause overflow.

The idea

An outcome assigned probability q has surprisal −ln(q). Smaller assigned probability means a larger cost when that outcome occurs. With natural logs the unit is a nat. The entropy of a distribution p averages that surprisal when the forecast is p itself. Cross-entropy averages the surprisal under forecast q while outcomes follow p.

H(p) = −Σᵢ pᵢ ln(pᵢ)

H(p, q) = −Σᵢ pᵢ ln(qᵢ)

Dₖₗ(p ‖ q) = H(p, q) − H(p)

The extra cost is KL divergence. If the target is a single observed class c, its cross-entropy reduces to −ln(q꜀).

A classifier often produces unnormalized scores called logits. Softmax exponentiates each score and divides by the sum. Exponentiating a score of 1000 directly overflows in typical floating-point arithmetic. Subtract the largest score from all scores first. This preserves the ratios between exponentials and makes the largest exponent zero.

Start with one class, then average over possible classes

If the observed class is c and the forecast gives it probability q꜀, the loss is −ln(q꜀). The symbol ln is the natural logarithm. At probability 1 the loss is 0. At probability 0.01 it is about 4.605. Assigning zero to an outcome that can occur gives an infinite loss in the mathematical model.

Let pᵢ be the probability of class i in the actual distribution and qᵢ the probability in the forecast. Over repeated draws from p, the expected forecast loss is the sum of each possible loss weighted by pᵢ. That is H(p, q). When the forecast equals p, the expected loss is H(p). Their difference is the extra expected cost of using q.

For a vector of logits z, softmax gives qᵢ = exp(zᵢ) / Σⱼ exp(zⱼ), where exp raises e to a power. Let m be the largest logit. Multiplying numerator and denominator by exp(−m) cancels the same factor from both. Taking the logarithm gives a stable formula.

log qᵢ = (zᵢ − m) − ln(Σⱼ exp(zⱼ − m)).

Work it out

Suppose the outcomes occur with probabilities p = (0.75, 0.25). Forecasting q = p costs about 0.562 nats on average. Forecasting (0.5, 0.5) costs −ln(0.5) ≈ 0.693 nats. The extra cost is about 0.131 nats.

For logits (1000, 1001, 1002), subtract 1002 to get (−2, −1, 0). The sum of the exponentials is about 1.5032. The last class has probability 1/1.5032 ≈ 0.6652, so the loss when it is correct is about 0.4076. Work in log space so you can compute the loss even when a tiny probability would round down to zero.

The expected log loss for a 75% event is lowest when the forecast is also 75%. Forecasting 50% gives a higher loss.

The lowest cross-entropy occurs when the forecast equals the true probability of 75%.

Run the Python lab

import numpy as np

def log_softmax(logits):
    shifted = logits - np.max(logits)
    return shifted - np.log(np.sum(np.exp(shifted)))

p = np.array([0.75, 0.25])
entropy = -p @ np.log(p)
cross_entropy = -p @ np.log(np.array([0.5, 0.5]))
logits = np.array([1000., 1001., 1002.])
log_probs = log_softmax(logits)

print(f"entropy: {entropy:.6f}")
print(f"uniform forecast: {cross_entropy:.6f}")
print(f"extra cost: {cross_entropy - entropy:.6f}")
print(f"loss for class 2: {-log_probs[2]:.6f}")

assert np.isclose(np.exp(log_probs).sum(), 1)
np.testing.assert_allclose(log_probs, log_softmax(logits - 1000))

Expected output

entropy: 0.562335
uniform forecast: 0.693147
extra cost: 0.130812
loss for class 2: 0.407606

Work in log space until you need a probability

The lab subtracts the largest logit before exponentiating. All shifted logits are nonpositive, so the largest exponential is 1. The denominator stays positive and cannot overflow for an ordinary class count. Subtracting the logarithm of that sum returns a vector of log probabilities. For one labelled example, take the negative entry for the observed class as the loss.

The assertion that probabilities sum to 1 checks normalization. The second assertion tests that shifting every logit by the same constant leaves the log probabilities unchanged. A small class probability can still round to zero if you exponentiate it, so read loss directly from log probabilities. Finally, distinguish a low training loss from well calibrated probabilities on new examples. Calibration needs its own held-out check.

Try it yourself

  1. Compare two forecasts for an event that actually happens. One assigns it probability 0.9 and the other assigns it 0.01. Compute both losses.
  2. Add 10,000 to every logit. Explain why the stable implementation produces the same probabilities.

Check your work. The costs are approximately 0.105 and 4.605 nats. The common logit offset cancels when we subtract the maximum.

Further reading

Deep Learning · Applied Math and Machine Learning Basics

Subject contents · Week 10 · Week 12