860. Fix the cross-entropy that returns inf
Why it matters Taking log of a softmax is the textbook way to get inf losses. Frameworks fuse log_softmax for exactly this reason.
The starter code below runs, but it has a realistic bug. Read the spec, find the bug and fix it. Keep the function name and signature.
cross_entropy(logits, labels) should return the mean negative log likelihood of the correct class: mean over rows of -log_softmax(logits)[i, labels[i]]. Compute log_softmax with the log-sum-exp trick so extreme logits give a finite answer.
Inputs: logits is a list or ndarray of shape (n, k). labels is a list or ndarray of n ints in [0, k).
Return a Python float. No rounding.
def cross_entropy(logits, labels)Example 1
Input: cross_entropy([[2.0, 0.0], [0.0, 2.0]], [0, 0])
Output: 1.1269
Example 2
Input: logits = [[0.0, 800.0]], labels = [0]
Output: 800.0
Example 3
Input: logits = [[1000.0, 0.0, 0.0], [0.0, 0.0, -900.0]], labels = [1, 2]
Output: 950.346574
Constraints
- Python 3 with NumPy. Code runs in your browser.
- Your code must pass all 4 tests to be accepted.
Hint 1
Print p for the confident and wrong test. What is log of that?
Hint 2
log(exp(z) / S) = z - log(S).
Hint 3
Index the log probabilities, not the probabilities.
Common mistakes
- Clipping p to 1e-12, which caps the loss at about 27.6 and gives the wrong value.
- Summing instead of averaging over rows.
- Using labels as one-hot when they are ints.
Understand the idea
After the max shift the softmax itself is safe, but a probability like exp(-800) underflows to 0.0, and log(0) is -inf. Staying in log space avoids it: log_softmax = z - logsumexp(z). For logits [0, 800] with label 0 the loss is exactly 800, not inf.
Shapes and data flow
logits: (n, k). labels: (n,). Output: scalar.