Math Fundamentals · lesson 11/15
Entropy & Information Theory
Entropy measures how much uncertainty a probability distribution carries, in bits or nats. It is the average surprise of a sample: common outcomes are cheap, rare outcomes are expensive. Cross-entropy and perplexity, the two numbers you watch during language model training, are both built from it.
The idea
For a discrete random variable with probabilities :
The quantity is the surprise (also called self-information) of outcome . Entropy is its expectation over the distribution. A certain event has , surprise , and contributes nothing.
Facts worth memorizing:
- Base sets the unit. gives bits; gives nats. One nat equals bits.
- Bounds. , with equality for a deterministic outcome. Among outcomes, is maximized by the uniform distribution at .
- Cross-entropy scores a model against the true . It satisfies , with equality only when .
- Perplexity is when using bits — an effective number of equally likely choices.
Worked example
A biased coin with and :
A fair coin gives exactly 1 bit, and a four-sided uniform die gives bits.
Now score a model that assigns probability to the observed class in 4-way classification with one-hot targets. Cross-entropy is nats, or bits. Since the true label is deterministic here, and all of the cross-entropy is error — that is the loss a classifier pushes down.
In code
import numpy as np
p = np.array([0.9, 0.1])
print(-(p * np.log2(p)).sum()) # 0.4690 bits
print(-(p * np.log(p)).sum()) # 0.3251 nats
q = np.array([0.1, 0.9])
print(-(p * np.log(q)).sum()) # 2.0829 nats cross-entropy
print((p * np.log(p / q)).sum()) # 2.0829 - 0.3251 = 1.7578 nats KLCross-entropy is -p log q summed; entropy is the special case q = p.
Check yourself
- What is the entropy of a fair 8-sided die, and in what units?
- Why is cross-entropy never less than entropy, and when are they equal?
- A language model reports 10 bits per token of cross-entropy. What is its perplexity?
Key takeaways
- Entropy is expected surprise; it is 0 for certainty and for a uniform -way choice.
- Cross-entropy measures a model against the truth and is minimized only by the true distribution.
- Perplexity is exponentiated cross-entropy, an interpretable effective vocabulary size.