Lesson 16 · Probability and information
Surprise: entropy, cross-entropy and KL divergence
The problem
In the softmax lesson, a model scored four toppings as . Softmax turned those scores into probabilities:
| Topping | Model's probability | What customers order, |
|---|---|---|
| pepperoni | 0.644 | 0.4 |
| margherita | 0.237 | 0.3 |
| veggie | 0.087 | 0.2 |
| hawaiian | 0.032 | 0.1 |
The right-hand column is what happens: over many orders, 40% are pepperoni, 30% margherita, and so on. The model is too keen on pepperoni and too stingy with hawaiian.
How good is the model, as one number? To train a model, we need that number, so we can make it smaller. This lesson builds it from one simple idea: surprise.
Surprise
When something unlikely happens, you're surprised. When something certain happens, you're not surprised at all. We want a number for that.
The surprise of an outcome with probability is:
As in the softmax lesson, is the natural log. Surprise is minus the log-probability. Some examples:
| Probability | Surprise |
|---|---|
| 1 | 0 |
| 0.5 | 0.693 |
| 0.1 | 2.303 |
| 0.01 | 4.605 |
Surprise measured with the natural log is in units called nats. Drag the dot along the curve below.
p = 0.50 → surprise = −log 0.50 = 0.69 nats
Drag the orange dot, or focus it and use the arrow keys.
Surprise of each topping, for p = (0.4, 0.3, 0.2, 0.1)
- pepperoni0.92
- margherita1.20
- veggie1.61
- hawaiian2.30
Why minus the log, and not something else, like ? Three reasons:
- Certain means zero. .
- Rarer means more surprising. As shrinks, grows.
- Surprises add up. Two independent orders, pepperoni (0.4) then hawaiian (0.1), have probability . Their surprise is , which equals . The log turns the product into a sum.
Predict first
An event has probability 0. What is its surprise?
Entropy: average surprise
Before each order arrives, how surprised do you expect to be? Some orders will be pepperoni (surprise 0.916), and some hawaiian (2.303). Take the average surprise, weighting each topping by how often it's ordered. That's an expectation.
Worked example
The average surprise of p = (0.4, 0.3, 0.2, 0.1)
Surprise of each topping: , , , .
This average surprise is the entropy of the distribution:
Read it as: for each outcome, its surprise times how often it happens, added up. An outcome with never happens, so it adds nothing. (We treat as 0.)
Entropy measures how unpredictable something is. Reshape the distribution below and watch the meter.
Predict first
Which is harder to predict: orders split 50/50 between pepperoni and margherita, or orders spread as (0.4, 0.3, 0.2, 0.1)?
Probabilities (weights ÷ their total)
- pepperoni0.40
- margherita0.30
- veggie0.20
- hawaiian0.10
H(p) = 0.40 × 0.92 + 0.30 × 1.20 + 0.20 × 1.61 + 0.10 × 2.30 = 1.280 nats
0 = certain · 1.386 = log 4, the most for four toppings (all equal)
Notice:
- Certain: . You're never surprised.
- Even split over 4 toppings: . No distribution over four outcomes has more entropy. With outcomes, the maximum is .
- Everything else is in between.
Entropy comes back in RL. Policy-gradient methods often add a bonus for the entropy of the policy, which stops an agent from becoming certain too early. It keeps the agent trying new actions.
Cross-entropy: how surprised is the model?
Now bring in the model. Real orders follow . But the model believes , so it feels surprise when topping arrives.
Predict first
A model gives a topping probability 0.01, and that topping is ordered. How big is the model's surprise?
Average the model's surprise over real orders and you get the cross-entropy:
Read it as: the outcomes happen as often as says (), but the surprise comes from the model ().
Worked example
Cross-entropy of the softmax model
The model's surprises: . These are minus the log-probabilities from the softmax lesson.
In practice, you don't know . You have a pile of real orders. So you average the model's surprise over those orders, and that average heads towards as the pile grows.
For a single order, the sum has one term: the model's surprise at the topping that was ordered. "Minus the log-probability of the right answer" is how classifiers are scored in practice.
Step through 300 orders below. Each order costs the model its surprise. The blue line is the running average.
Model q = (0.64, 0.24, 0.09, 0.03) · real orders follow p = (0.4, 0.3, 0.2, 0.1)
Order 0: none yet
Average so far: –
Cross-entropy H(p, q) = 1.440 · entropy H(p) = 1.280
Compare the four models:
| Model | Cross-entropy |
|---|---|
| Perfect: | 1.280 |
| Even split: 0.25 each | 1.386 |
| Softmax model | 1.440 |
| Overconfident: 0.97 on pepperoni | 2.775 |
The even split beats the softmax model. Guessing "no idea" costs less than being confidently lopsided. The overconfident model is the worst by far. Every non-pepperoni order costs it .
Nothing beats the perfect model. Its cross-entropy equals the entropy, . This is always true: , with equality only when . The entropy of reality is a floor no model can get below.
That's why cross-entropy is the standard way to train classifiers. Lower cross-entropy means the model's probabilities are closer to reality. As a training objective it's called the cross-entropy loss.
KL divergence: the extra cost
The softmax model's cross-entropy is 1.440. The floor is 1.280. The gap between them, 0.160 nats per order, is the extra surprise the model suffers because it believes instead of .
That gap is the KL divergence (KL for Kullback–Leibler, the two people who introduced it):
The second form comes from subtracting the two sums term by term: . Read as "the KL divergence of from ", or "how much worse does than , when reality is ".
So cross-entropy splits into two parts:
For the softmax model: .
When you train a model, is fixed by the data, so can't change. The only part training can shrink is the KL divergence. So minimising cross-entropy is the same as minimising KL divergence: it pulls the model's towards the real .
Shape the model's distribution below. The stacked bar shows the split.
- pepperonip 0.40q 0.64
- margheritap 0.30q 0.24
- veggiep 0.20q 0.09
- hawaiianp 0.10q 0.03
H(p, q) = 1.280 + 0.160 = 1.440
KL(p ‖ q) = 0.160 · KL(q ‖ p) = 0.142
Green: entropy of p (fixed). Orange: the extra cost of using q.
Predict first
KL(p ‖ q) for the overconfident model is 1.495. What is KL(q ‖ p), with the two swapped?
- KL is never negative. It's zero only when .
- KL isn't symmetric. In general, . So it's not a true distance. It's still a useful measure of mismatch.
- KL can be infinite. If for an outcome that says can happen, the term is infinite.
KL shows up all over ML. Some RL methods use it to stop a policy from changing too much in one update. Examples are TRPO (trust region policy optimisation) and some versions of PPO (proximal policy optimisation). Language-model fine-tuning uses it to keep a tuned model close to the original.
DeeperWhich way round? Forward vs reverse KLWhen the model can't match reality exactly, the two directions of KL prefer very different compromises. · 4 min
Say customers come in two types. Half love pepperoni, half love hawaiian, and almost nobody orders the middle two. So has two peaks. A peak of a distribution is called a mode.
Now say the model can only make one peak, or spread out evenly. Compare two options:
| Model | ||
|---|---|---|
| Even spread: | 0.368 | 0.511 |
| One peak: | 0.703 | 0.431 |
The two directions disagree about which model is better. Switch between the two models below.
- pepperonip 0.45q 0.25
- margheritap 0.05q 0.25
- veggiep 0.05q 0.25
- hawaiianp 0.45q 0.25
Forward KL(p ‖ q) = 0.368 · reverse KL(q ‖ p) = 0.511
Forward KL prefers: even spread. Reverse KL prefers: one peak.
Forward KL, , prefers the spread. It weights by , so it cares most about the things that happen.
The one-peak model gives hawaiian only 0.05, though 45% of orders are hawaiian. That's heavily punished. So forward KL pushes the model to cover everything that happens, even if it puts probability where nothing happens. This is called mode-covering. Training with cross-entropy minimises forward KL.
Reverse KL, , prefers one peak. It weights by , so it cares most about where the model puts probability.
The spread model puts 0.25 on each of veggie and margherita, which reality almost never orders, and that's punished. The one-peak model puts its probability where orders happen. Reverse KL pushes the model to sit on one peak and ignore the rest. This is called mode-seeking.
Which you want depends on the job. Variational inference, used in variational autoencoders (VAEs), minimises reverse KL. Ordinary classifier training uses forward KL, through cross-entropy.
DigressionBits and Shannon's ideaMeasure surprise with log base 2 and entropy counts yes/no questions. · 3 min
Claude Shannon introduced entropy in 1948, in a paper about sending messages efficiently ("A Mathematical Theory of Communication"). He used log base 2, which measures surprise in bits.
With base 2, a fair coin flip has surprise bit. Four equally likely toppings have entropy bits. That's the number of yes/no questions you need to pin down the order: "Is it pepperoni or margherita?", then "Which of the two?"
Shannon showed that entropy is the smallest average number of bits per message you can achieve when encoding messages from a source. Our orders, , have entropy bits. A clever code uses short codes for common toppings and long ones for rare ones, and gets close to 1.846 bits per order.
Cross-entropy fits this picture too. It's the average length you get if you design your code for but the messages follow . KL is the wasted length.
Nats and bits differ only by a constant factor: 1 nat = bits. This book uses nats, as most ML code does.
For continuous outcomes, sums become integrals over a density. KL works the same way there; entropy needs more care.
Common misconceptions
"Entropy is a property of the model." Entropy belongs to one distribution. Cross-entropy compares two: what happens, and what the model believes.
"Cross-entropy can be zero for a good model." Only if reality is certain. The best possible cross-entropy is , which is 1.280 for our toppings.
"KL is a distance." It's never negative and is zero only for identical distributions, but it isn't symmetric. Always say which way round you mean.
"Lower cross-entropy always means a more accurate model." It means better probabilities. A model can pick the right top topping (accurate) while being badly overconfident (high cross-entropy), like the overconfident model here.
Recap
- Surprise is : zero when certain, large when rare, and it adds up over independent events.
- Entropy is the average surprise. It's 0 for a certain outcome and for equally likely ones.
- Cross-entropy is a model's average surprise at real outcomes. It's never below .
- KL divergence is the extra surprise from using . It isn't symmetric.
- Minimising cross-entropy minimises KL, pulling the model towards reality.
Section 2 shows how to compute these in PyTorch.