Numerically stable softmax and cross-entropy
Problem
logits has shape (N, C); labels holds N integer class indices. Return (probs, mean_loss): the row-wise softmax probabilities and the mean negative log-likelihood. It must stay finite for logits up to ±1000.
Signature
def softmax_cross_entropy(logits: list[list[float]], labels: list[int]) -> tuple[np.ndarray, float]: ...Examples
The visible tests, as an interactive Python session would show them: each call and the value it should give.
>>> close(softmax_cross_entropy([[0.0, 0.0]], [1]), ([[0.5, 0.5]], 0.693147))
True
>>> close(softmax_cross_entropy([[1000.0, 1000.0]], [0]), ([[0.5, 0.5]], 0.693147))
TrueHints
Subtract the row max before exp — avoid overflow.
log probabilities as (z - max) - log(sum(exp(z - max))); loss is the negative mean of the label term.
Use fancy indexing for the label terms; the mean is over examples, not classes.
Reference solution
import numpy as np
def softmax_cross_entropy(logits, labels):
z = np.asarray(logits, dtype=float)
z = z - z.max(axis=1, keepdims=True)
logp = z - np.log(np.exp(z).sum(axis=1, keepdims=True))
p = np.exp(logp)
loss = -logp[np.arange(len(labels)), labels].mean()
return p, float(loss)What a strong solution covers
- Subtracts the row max (log-sum-exp).
- Computes the loss from log-probabilities rather than log(softmax).
- Uses fancy indexing for the label terms.
- States the gradient
softmax − one_hot.
Common mistakes
np.log(np.exp(z).sum())overflowing- averaging over classes instead of examples.