Measure uncertainty under a distribution and the extra log loss incurred by predicting with another.
65 minYou need Module 1 and logarithms
In this module you will
Compute entropy and cross-entropy for finite distributions
Identify when a zero predicted probability gives infinite loss
Interpret KL divergence as the excess expected log loss
1
Surprise and entropy
An outcome with probability pi>0 has surprise −logpi. Use the natural logarithm throughout this series, so values are in nats. Use base two instead to measure bits. Entropy averages surprise under the true distribution p:
H(p)=−i:pi>0∑pilnpi.
A deterministic distribution has entropy zero. A uniform distribution on K outcomes has entropy lnK. Terms with zero weight contribute zero by continuity.
2
Prediction under a different distribution
A model q assigns surprise −lnqi. Averaging over the data distribution gives H(p,q)=−∑i:pi>0pilnqi. If any qi=0 with pi>0, this loss is +∞. Subtracting the true entropy yields
DKL(p∥q)=i:pi>0∑pilnqipi=H(p,q)−H(p).
To see why it is nonnegative, apply −lnx≥1−x to x=qi/pi on the positive support of p. The resulting lower bound is 1−∑i:pi>0qi≥0. Equality requires p=q. Swapping p and q changes which distribution weights each term, so KL is generally asymmetric.
Example 3.1Compare a fair model and a biased source✓ Checked
If p=(3/4,1/4) and q=(1/2,1/2), then H(p,q)=ln2. The source entropy is about 0.5623 nats and the excess loss is about 0.1308 nats.
Try it
Set the source weights to 3, 1, 0 and the predicted weights to 1, 1, 0. Select nats to reproduce the worked example. Then set the second predicted weight to zero and check which direction of KL divergence becomes infinite.
Compute itAverage surprise
Calculate the scores using the same units throughout.
Python
from math import log
p, q = (0.75, 0.25), (0.5, 0.5)
entropy = -sum(pi * log(pi) for pi in p if pi > 0)
cross_entropy = -sum(pi * log(qi) for pi, qi inzip(p, q) if pi > 0)
print(f"{entropy:.4f} {cross_entropy:.4f} {cross_entropy - entropy:.4f}")
Output
0.5623 0.6931 0.1308
3
Exercises
Exercise 3.1★Uniform source
Compute the entropy in nats for four equally probable tokens.
Show solution✓ Checked
Each token has surprise ln4. Its average is ln4.
Exercise 3.2★★A deterministic source
Compute the excess loss when p=(1,0) and q=(1/4,3/4).
Show solution✓ Checked
H(p)=0, and the only outcome that occurs incurs loss −ln(1/4)=ln4.
Exercise 3.3★★★Change the units
Convert the entropy of eight equally probable outcomes from nats to bits.
Show solution✓ Checked
Divide ln8 by ln2 to obtain 3 bits.
4
Check yourself
1
Which distribution supplies the weights in H(p,q)?
The loss under q is averaged over outcomes from p.
2
What if pi>0 and qi=0?
The model gives no probability to a possible observed outcome.
3
When is DKL(p∥q)=0?
Zero excess expected log loss requires agreement of the distributions.