Part 3 of 6 · The loss and its gradientLearn and do
Take the log of a sum, never the log of a probability
Subtracting each row's max keeps np.exp finite. The log has a trap of its own.
z = np.array([0.0, -40000.0, 3.0])z = z - z.max()probs = np.exp(z) / np.exp(z).sum()print(probs)print(-np.log(probs[1]))log_probs = z - np.log(np.exp(z).sum())print(-log_probs[1])
Predict
The label is class 1, whose logit sits 40,003 below the top. Its probability rounds to 0.0. What do -np.log(probs[1]) and the log-space line give?
Pick one to see what it prints.
Route
What you hold for label 1
Loss
The log of a probability
p = 0.0 in float64
-log(0.0) = inf
Log space, never forming p
log p = -40003 - 0.05
40003.05
The log-space formula, for each logit zk in a row:
logpk=(zk−m)−logj∑ezj−m
Here m is the row's largest logit, and the sum runs over the row's K logits. The code above does it for one row. For a batch of rows, take the max and the sum along axis 1, with keepdims=True so each row's max and each row's sum stay lined up with that row.
This happens in the practice tests. With W2 scaled up, one example has a label probability of about e−39241, which underflows to exactly 0.0. np.log(probs) turns that into -inf and the loss into inf. The log-space formula reports that example's loss as 39,241 and the batch mean as 6,540.2.
The gradient is safe either way. It needs only the probabilities, np.exp(log_probs). One that underflows to 0 just makes that entry of dlogits equal to (0−1)/N.
PyTorch takes the same route. Its CrossEntropyLoss expects raw logits and applies the log-softmax itself. Hand it logits, never probabilities.
In the editor, write mean_cross_entropy(logits, y): the log-space formula for every row, then the mean of minus each label's log-probability.
Pick an answer above to see the rest
Instructions
1
Write mean_cross_entropy(logits, y) for (N, K) logits and (N,) integer labels. It has to stay finite with logits in the tens of thousands, and when a label's probability underflows to 0.