Maths toolkit16 / 17

Lesson 16 · Probability and information

Surprise: entropy, cross-entropy and KL divergence

The problem

In the softmax lesson, a model scored four toppings as (2,1,0,−1)(2, 1, 0, -1). Softmax turned those scores into probabilities:

ToppingModel's probability qqWhat customers order, pp
pepperoni0.6440.4
margherita0.2370.3
veggie0.0870.2
hawaiian0.0320.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 pp is:

surprise=−log⁡p\text{surprise} = -\log p

As in the softmax lesson, log⁡\log is the natural log. Surprise is minus the log-probability. Some examples:

Probability ppSurprise −log⁡p-\log p
10
0.50.693
0.12.303
0.014.605

Surprise measured with the natural log is in units called nats. Drag the dot along the curve below.

00.20.40.60.81012345probability psurprise −log p

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
Surprise is −log p. A certain event (p = 1) has surprise 0. As p heads towards 0, surprise grows without limit. Each tenfold drop in probability adds the same 2.303.

Why minus the log, and not something else, like 1−p1 - p? Three reasons:

  • Certain means zero. −log⁡1=0-\log 1 = 0.
  • Rarer means more surprising. As pp shrinks, −log⁡p-\log p grows.
  • Surprises add up. Two independent orders, pepperoni (0.4) then hawaiian (0.1), have probability 0.4×0.1=0.040.4 \times 0.1 = 0.04. Their surprise is −log⁡0.04=3.219-\log 0.04 = 3.219, which equals 0.916+2.3030.916 + 2.303. 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)

  1. Surprise of each topping: −log⁡0.4=0.916-\log 0.4 = 0.916, −log⁡0.3=1.204-\log 0.3 = 1.204, −log⁡0.2=1.609-\log 0.2 = 1.609, −log⁡0.1=2.303-\log 0.1 = 2.303.

This average surprise is the entropy of the distribution:

H(p)=∑ipi (−log⁡pi)=−∑ipilog⁡piH(p) = \sum_i p_i \,(-\log p_i) = -\sum_i p_i \log p_i

Read it as: for each outcome, its surprise times how often it happens, added up. An outcome with pi=0p_i = 0 never happens, so it adds nothing. (We treat 0×log⁡00 \times \log 0 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)

Entropy is zero when one topping is certain and largest, log 4 = 1.386, when all four are equally likely. Spreading probability over more toppings raises it; piling it onto one lowers it.

Notice:

  • Certain: H=1×0=0H = 1 \times 0 = 0. You're never surprised.
  • Even split over 4 toppings: H=log⁡4=1.386H = \log 4 = 1.386. No distribution over four outcomes has more entropy. With nn outcomes, the maximum is log⁡n\log n.
  • 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 pp. But the model believes qq, so it feels surprise −log⁡qi-\log q_i when topping ii 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:

H(p,q)=∑ipi (−log⁡qi)H(p, q) = \sum_i p_i \,(-\log q_i)

Read it as: the outcomes happen as often as pp says (pip_i), but the surprise comes from the model (−log⁡qi-\log q_i).

Worked example

Cross-entropy of the softmax model

  1. The model's surprises: −log⁡(0.644, 0.237, 0.087, 0.032)=(0.440, 1.440, 2.440, 3.440)-\log(0.644,\ 0.237,\ 0.087,\ 0.032) = (0.440,\ 1.440,\ 2.440,\ 3.440). These are minus the log-probabilities from the softmax lesson.

In practice, you don't know pp. You have a pile of real orders. So you average the model's surprise over those orders, and that average heads towards H(p,q)H(p, q) as the pile grows.

For a single order, the sum has one term: the model's surprise −log⁡q-\log q 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)

05010015020025030000.511.522.533.5orders so faraverage surprise

Order 0: none yet

Average so far: –

Cross-entropy H(p, q) = 1.440 · entropy H(p) = 1.280

Order 0 of 300
Each real order costs the model −log q(order). The running average settles on the cross-entropy (orange dashed). On average, no model gets below the entropy of the orders (green dashed), and only the perfect model reaches it.

Compare the four models:

Model qqCross-entropy H(p,q)H(p, q)
Perfect: q=pq = p1.280
Even split: 0.25 each1.386
Softmax model1.440
Overconfident: 0.97 on pepperoni2.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 −log⁡0.01=4.605-\log 0.01 = 4.605.

Nothing beats the perfect model. Its cross-entropy equals the entropy, H(p,p)=H(p)=1.280H(p, p) = H(p) = 1.280. This is always true: H(p,q)≥H(p)H(p, q) \ge H(p), with equality only when q=pq = p. 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 qq instead of pp.

That gap is the KL divergence (KL for Kullback–Leibler, the two people who introduced it):

DKL(p ∥ q)=H(p,q)−H(p)=∑ipilog⁡piqiD_{\mathrm{KL}}(p \,\Vert\, q) = H(p, q) - H(p) = \sum_i p_i \log \frac{p_i}{q_i}

The second form comes from subtracting the two sums term by term: pi(−log⁡qi)−pi(−log⁡pi)=pilog⁡(pi/qi)p_i(-\log q_i) - p_i(-\log p_i) = p_i \log(p_i / q_i). Read DKL(p ∥ q)D_{\mathrm{KL}}(p \,\Vert\, q) as "the KL divergence of qq from pp", or "how much worse qq does than pp, when reality is pp".

So cross-entropy splits into two parts:

H(p,q)⏟model’s surprise=H(p)⏟reality’s own unpredictability+DKL(p ∥ q)⏟extra, from the wrong model\underbrace{H(p, q)}_{\text{model's surprise}} = \underbrace{H(p)}_{\text{reality's own unpredictability}} + \underbrace{D_{\mathrm{KL}}(p \,\Vert\, q)}_{\text{extra, from the wrong model}}

For the softmax model: 1.440=1.280+0.1601.440 = 1.280 + 0.160.

When you train a model, pp is fixed by the data, so H(p)H(p) 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 qq towards the real pp.

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.

The green part, H(p), is fixed by the real orders. The orange part, KL(p ‖ q), is the extra cost of the model's mistakes. Make q match p and the orange part vanishes. The readout also shows KL the other way round, KL(q ‖ p): usually a different number.

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 q=pq = p.
  • KL isn't symmetric. In general, DKL(p ∥ q)≠DKL(q ∥ p)D_{\mathrm{KL}}(p \,\Vert\, q) \ne D_{\mathrm{KL}}(q \,\Vert\, p). So it's not a true distance. It's still a useful measure of mismatch.
  • KL can be infinite. If qi=0q_i = 0 for an outcome that pp says can happen, the term pilog⁡(pi/0)p_i \log(p_i / 0) 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 p=(0.45, 0.05, 0.05, 0.45)p = (0.45,\ 0.05,\ 0.05,\ 0.45) 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 qqDKL(p ∥ q)D_{\mathrm{KL}}(p \,\Vert\, q)DKL(q ∥ p)D_{\mathrm{KL}}(q \,\Vert\, p)
Even spread: (0.25, 0.25, 0.25, 0.25)(0.25,\ 0.25,\ 0.25,\ 0.25)0.3680.511
One peak: (0.85, 0.05, 0.05, 0.05)(0.85,\ 0.05,\ 0.05,\ 0.05)0.7030.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.

Grey bars: the two-peaked p. Coloured bars: the model q. Forward KL prefers the even spread; reverse KL prefers one peak.

Forward KL, DKL(p ∥ q)D_{\mathrm{KL}}(p \,\Vert\, q), prefers the spread. It weights by pp, 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, DKL(q ∥ p)D_{\mathrm{KL}}(q \,\Vert\, p), prefers one peak. It weights by qq, 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 −log⁡20.5=1-\log_2 0.5 = 1 bit. Four equally likely toppings have entropy log⁡24=2\log_2 4 = 2 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, p=(0.4,0.3,0.2,0.1)p = (0.4, 0.3, 0.2, 0.1), have entropy 1.280/log⁡2=1.8461.280 / \log 2 = 1.846 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 qq but the messages follow pp. KL is the wasted length.

Nats and bits differ only by a constant factor: 1 nat = 1/log⁡2≈1.4431 / \log 2 \approx 1.443 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 H(p)H(p) belongs to one distribution. Cross-entropy H(p,q)H(p, q) 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 H(p)H(p), 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 −log⁡p-\log p: zero when certain, large when rare, and it adds up over independent events.
  • Entropy H(p)H(p) is the average surprise. It's 0 for a certain outcome and log⁡n\log n for nn equally likely ones.
  • Cross-entropy H(p,q)H(p, q) is a model's average surprise at real outcomes. It's never below H(p)H(p).
  • KL divergence DKL(p ∥ q)=H(p,q)−H(p)D_{\mathrm{KL}}(p \,\Vert\, q) = H(p, q) - H(p) is the extra surprise from using qq. It isn't symmetric.
  • Minimising cross-entropy minimises KL, pulling the model towards reality.

Section 2 shows how to compute these in PyTorch.