Part 02 / Topic 6 of 7
Softmax and log probabilities
A classifier ends with one raw score per class (logits). Softmax turns them into probabilities: exponentiate, then normalise. The outputs are between 0 and 1 and sum to 1.
Done naively, exp() overflows on big logits. The fix — used by every real implementation — is to subtract the max first; the result is unchanged.
# examples/03_softmax_and_why_we_subtract_the.py
import numpy as np
def softmax_naive(z):
e = np.exp(z)
return e / e.sum()
def softmax(z):
e = np.exp(z - z.max()) # same result, no overflow
return e / e.sum()
z = np.array([2.0, 1.0, 0.1])
print("softmax:", softmax(z).round(4), "sum =", softmax(z).sum())
# softmax: [0.659 0.2424 0.0986] sum = 1.0
big = np.array([1000.0, 999.0])
with np.errstate(over="ignore", invalid="ignore"):
print("naive on large logits :", softmax_naive(big))
print("stable on large logits:", softmax(big).round(4))
# naive on large logits : [nan nan]
# stable on large logits: [0.7311 0.2689]
Probabilities multiply; tiny numbers underflow. So ML works with log probabilities, which add instead:
probs = np.array([0.659, 0.2424, 0.0986])
print(np.log(probs).round(3)) # [-0.417 -1.417 -2.317]
# product of probs == exp of summed logs
print(probs.prod().round(6)) # 0.015751
print(np.exp(np.log(probs).sum()).round(6)) # 0.015751
Cross-entropy loss (Stage 3) is just the negative log probability of the right class.
🧪 Quick quiz
- Why does a stable softmax subtract max(z) first?
Show the answer
To avoid overflow in exp() without changing the result — exp(1000) overflows and the naive version returns NaN; subtracting the max gives [0.7311, 0.2689].
Done here? The practice set for Part 2 — 4 exercises with solutions — is on the part page.