Surprise, bits and entropy
Before this lesson: discrete random variables and expectation (the probability track) and the rules of logarithms (Foundations 04). This is the first lesson of the track. Time: about 50 minutes, plus the notebook.
Why this matters #
A classifier or a language model is trained with the cross-entropy loss: the average surprisal of the true label (or the next token) under the model. The entropy of the data is the lowest value this loss can reach (lesson 04). Entropy is also the smallest average number of bits per symbol of any lossless compressor (lesson 05). Beyond losses, entropy appears directly in many algorithms: decision trees choose splits that lower the entropy of the labels, active learning asks for labels where the model's prediction has high entropy, soft actor-critic (SAC) rewards policies with high entropy, and the temperature of a language model controls the entropy of the next-token distribution. Every later lesson of this track builds on the definitions here.
1. Predict first #
2. The picture #
Surprise is measured with a logarithm #
Think of an outcome with probability . If , seeing tells you nothing new. If is small, seeing is surprising and tells you a lot. The surprisal (also called the information content or self-information) of is
| Outcome | Surprisal | |
|---|---|---|
| a sure event | bits | |
| heads with a fair coin | bit | |
| two heads with two fair coins | bits | |
| one card from 8 equally likely cards | bits | |
| a six with a fair die | bits | |
| a 1-in-1000 event | bits |
Why a logarithm? Take two independent events, for example two coin flips. Their probabilities multiply: two heads have probability . The information should add: one bit for each flip, two bits in total. The logarithm is the function that turns products into sums:
A consequence: halving a probability adds exactly one bit, because .
Slide and watch the yellow point move on the blue curve . Press Halve p a few times: each press adds exactly one bit. The faint point at is always one bit higher. Switch to two independent outcomes: the surprisal of "both happen" (probability ) is the sum of the two surprisals. The log scale axis turns the curve into a straight line.
The question game #
A friend picks one of 8 cards, all equally likely. You may ask only yes/no questions. Ask "Is it one of cards 1–4?": the answer removes half of the cards. Two more halving questions find the card. So you need questions. In general, finding one of equally likely items takes questions. With 20 questions you can find one item among one million.
Now let the outcomes have different probabilities: with , with , with . Good strategy: ask about the likely outcome first.
- Ask "Is it ?". Half of the time the answer is yes: 1 question.
- If no, ask "Is it ?". This finds or : 2 questions.
The average number of questions is . Look at the surprisals: and . Each outcome needs as many questions as its surprisal. So the average number of questions is the average surprisal. This average is the entropy.
Press Play once to draw a hidden outcome and follow its path in the question tree (yellow). Then press Play 100 games a few times: the running average settles at the expected number of questions of the tree (grey line). For this equals the entropy bits (blue line). Try the strategy split the list in half: it needs 2 questions. Then try the distribution : even the best tree needs more than , because surprisals such as bits are not whole numbers.
When the probabilities are not powers of , the best question tree needs a little more than the entropy, but always less than the entropy plus one question. If you find many outcomes together (for example, ask about 10 die rolls at once), the average per outcome comes as close to the entropy as you want. Lesson 05 proves both facts.
Entropy is the average surprisal #
The entropy of a coin with :
The rare outcome is very surprising (3.3 bits), but it is rare. The common outcome is almost no surprise. On average you learn less than half a bit per flip.
Drag the tops of the blue bars (the probabilities); the other bars rescale so the total stays 1. The yellow bars below are the contributions of each outcome; their sum is the entropy . Use one-hot and uniform to reach the two extremes and (the dashed line in the meter). Notice that a tiny probability contributes almost nothing, and so does a probability close to 1.
A fair 8-sided die is rolled. What is the entropy of the result?
Each face has probability and surprisal bits, so the average is 3 bits: three halving questions find the face. 8 is the number of outcomes, not the entropy; 2.08 is , the entropy in nats, not in bits.
Which distribution on 4 outcomes has the largest entropy?
The uniform distribution is the hardest to guess: bits. The others have , and bit. A large single probability makes the outcome easy to guess, so it lowers the entropy; it does not raise it.
3. Definitions and main results #
Entropy #
Let be a discrete random variable with values in a finite set of size , and let .
- The surprisal of a value with is .
- The entropy of is the expected surprisal:
- Convention: . The reason: as . An outcome with probability 0 never happens, so it adds nothing to the average.
We also write for the entropy of a distribution .
Entropy depends only on the list of probabilities. The values of do not enter the formula. A coin with values and a variable with values , each with probability , both have entropy 1 bit. Relabeling or reordering the outcomes does not change . Adding an outcome with probability 0 does not change either.
Units: bits and nats #
Changing the base of the logarithm only multiplies by a constant, because :
For example, the distribution has entropy bits nats.
The binary entropy #
A variable with two outcomes, with probabilities and , has the binary entropy
Its properties, read off the curve below:
- : a sure outcome has no uncertainty.
- bit, the maximum.
- : swapping the two labels does not change the entropy.
- The curve is steep near and : moving from to already gives bits. Some values: , , bits.
Drag the first bar from 0 to 1. The yellow point runs along the binary entropy curve (blue). Notice the symmetry around and how fast the curve rises near the ends.
A coin lands heads with probability . What is its entropy?
bits. The rare outcome is very surprising, but it has weight only in the average. bits is the surprisal of heads alone, not the average over both outcomes.
Bounds on the entropy #
Theorem (bounds on entropy). Let take values. Then
if and only if is constant (one value has probability 1). if and only if is uniform on all values.
Proof of the lower bound.
- Every lies in , so , and every term is .
- A sum of non-negative terms is non-negative, so .
- means every term is 0. The term is 0 only for or . So every probability is 0 or 1: one value has probability 1.
Intuition for the upper bound. The uniform distribution is the hardest to guess: no outcome is more likely than another, so no question strategy can do better than halving. Any bias makes some outcomes easier to guess, which lowers the average number of questions.
The proof uses one simple inequality.
Lemma. for all , with equality only at .
Proof. Let . Then , which is negative for and positive for . So has its minimum at , where . Hence , with equality only at . As a picture: the line touches the curve at and lies above it everywhere else.
Proof of the upper bound.
- Let be the support of . Terms with are 0, so . Work in nats; bits only divide both sides by .
- Since , we can write . Subtract:
- Apply the lemma with to every term:
because the support has at most elements.
- Equality needs equality in both steps. The lemma is tight only when , that is for every . The last step is tight only when . Together: for all values.
Lesson 03 gives a second view of the same fact: is the KL divergence from to the uniform distribution, which is never negative.
Doubling the number of equally likely outcomes adds one bit: . A uniform choice among 1024 items has 10 bits; among 2048 items, 11 bits.
takes the values and with probability each. takes the values and with probability each. Compare their entropies.
Entropy uses only the probabilities, never the values. Both variables are a fair choice between two outcomes, so both have 1 bit. The spread of the values is measured by the variance, which is a different quantity.
Why exactly the logarithm?
Suppose a measure of surprise depends only on the probability , is continuous, and adds for independent events: . Put for . Then , and a continuous function with this property is linear (Cauchy's functional equation): . So . The constant only chooses the unit: gives , that is, bits. For a positive surprise, .
Shannon (1948, Theorem 2) proved a similar statement for the entropy itself: the only continuous function of that grows with for uniform distributions and that obeys a natural "grouping" rule (one question at a time, as in the question game) is .
A preview of coding #
A code writes each outcome as a string of bits. For on , use , , , . The bits are the answers in the question game: 0 for "yes", 1 for "no". The average length is bits, exactly the entropy: each codeword length equals the surprisal of its symbol. No code that can always be decoded does better on average than the entropy; this is the source coding theorem of lesson 05.
Answers to section 1. (1) Between 2 and 3. The entropy of a fair die is bits. The best question tree for one die puts 2 faces at depth 2 and 4 faces at depth 3, so it needs questions on average. Asking about many dice at once brings the average per die close to (lesson 05). (2) Less than both: bits. (3) No. Every term is , so .
4. Worked example #
(a) A weather forecast. Tomorrow is sunny with probability , cloudy with , rainy with and snowy with .
- Surprisals. , , , bits.
- Entropy in bits. Weight each surprisal by its probability: bits.
- In nats. Multiply by : nats.
- Compare with the maximum. For , bits. The forecast is less uncertain than a uniform choice among 4, because "sunny" is likely.
- Question tree. Ask "sunny?", then "cloudy?", then "rainy?". The numbers of questions are 1, 2, 3, 3: equal to the surprisals. The average is 1.75 questions .
(b) Probabilities that are not powers of . on .
- Surprisals. , , bits.
- Entropy. bits.
- Best question tree. Ask "Is it ?", then "Is it ?". The numbers of questions are 1, 2, 2, so the average is questions.
- Check the bounds. : the best tree is above the entropy but within one question of it. The maximum for is bits.
(c) Temperature in a softmax. A model outputs the logits for three classes. The probabilities are with the temperature .
- : , bits.
- divides by a smaller number, so the gaps between logits grow: , bits.
- shrinks the gaps: , bits.
Higher temperature, higher entropy, closer to the maximum bits.
A source has the distribution . What is its entropy?
The surprisals are 1, 2, 3, 4, 4 bits. The average is bits. is the maximum for 5 outcomes, reached only by the uniform distribution.
5. In code #
NumPy computes the entropy of a probability vector. Skipping the zeros implements the convention ; writing the terms as makes the result exactly for a sure outcome.
import numpy as np
from scipy.stats import entropy
def H(p, base=2):
"""Entropy of a probability vector; terms with p = 0 are skipped (0 log 0 = 0)."""
p = np.asarray(p, dtype=float)
p = p[p > 0]
return np.sum(p * np.log(1 / p)) / np.log(base)
weather = [1/2, 1/4, 1/8, 1/8]
print(-np.log2(weather)) # [1. 2. 3. 3.] surprisals in bits
print(H(weather), H(weather, base=np.e)) # 1.75 1.2130075659799042
print(entropy(weather, base=2)) # 1.75 SciPy agrees
print(H([0.9, 0.1]), H([0.7, 0.2, 0.1])) # 0.46899559358928133 1.1567796494470395
print(H([1, 0, 0]), H(np.ones(8) / 8), H(np.ones(6) / 6)) # 0.0 3.0 2.584962500721156
def softmax(z, T=1.0):
z = np.asarray(z, dtype=float) / T
e = np.exp(z - z.max()) # subtract the max for numerical safety
return e / e.sum()
for T in [0.5, 1, 2]:
q = softmax([2, 1, 0], T)
print(T, q.round(3), round(H(q), 3))
# 0.5 [0.867 0.117 0.016] 0.636
# 1 [0.665 0.245 0.09 ] 1.201
# 2 [0.506 0.307 0.186] 1.472
scipy.stats.entropy(p) normalizes p first and uses nats unless you pass base. A plain
np.sum(p * np.log(p)) returns nan when some p is 0, because 0 * log(0) is 0 * (-inf).
6. Where it shows up #
- Loss functions. The cross-entropy loss of a classifier is the average surprisal of the true label under the model. It can never go below the entropy of the labels given the inputs (lesson 02 and lesson 04). A language model's loss in bits per token is the average surprisal of the next token.
- Decision trees. The entropy of the class labels at a node measures how mixed the node is. ID3 and C4.5 choose the split with the largest information gain, the drop in entropy (lesson 02 and the decision-tree lesson of the ML fundamentals track, in preparation).
- Uncertainty of a prediction. The entropy of a classifier's predicted distribution is a simple uncertainty score. Uncertainty sampling in active learning asks for labels of the inputs with the highest predictive entropy.
- Reinforcement learning. Soft actor-critic (SAC) maximizes reward plus times the entropy of the policy, and PPO often adds an entropy bonus. Both keep the policy random enough to explore (RL 08).
- Sampling from language models. Dividing the logits by a temperature raises the entropy of the next-token distribution (more varied text); lowers it (more predictable text) (the decoding lesson of the LLMs track, in preparation).
- ML for science. In biology, a sequence logo shows, for each position of aligned DNA or protein sequences, the information content , where is the alphabet size (4 for DNA, 20 for proteins) and is the entropy of the letters in that column. Conserved positions have low entropy and tall letters. In ecology, the entropy of species proportions is the Shannon diversity index.
7. Common mistakes #
- Mixing bits and nats. NumPy, SciPy (by default) and PyTorch use the natural log. Divide by to get bits.
nanfrom . Skip the zero probabilities, or usescipy.special.xlogy. The convention is .- "Entropy measures how spread out the values are." It does not use the values at all. and with equal probabilities both have 1 bit. Spread of values is the variance.
- Confusing the average surprisal with the surprisal of the likely outcome. For the likely outcome has surprisal bits, but the entropy is bits.
- Using counts instead of probabilities. The formula needs probabilities that sum to 1. Divide
counts by their total first. (
scipy.stats.entropydoes this for you; a hand-written formula does not.) - Expecting entropy to grow like . The entropy of a uniform distribution grows like : doubling the number of outcomes adds only one bit.
8. Check yourself #
- What is the entropy of a fair six-sided die, in bits and in nats?
Answer
bits and nats. - Which has more entropy: a coin with or a coin with ?
Answer
bits and bits. The coin with is closer to , so it has more entropy. - Someone says a distribution on 5 outcomes has entropy 2.5 bits. Is this possible?
Answer
No. The maximum for 5 outcomes is bits, reached by the uniform distribution. - A uniform distribution has entropy 5 bits. How many outcomes does it have? What is the entropy if
you double the number of outcomes?
Answer
gives . With 64 equally likely outcomes, bits: doubling adds one bit. - Prove that implies that one value of has probability 1.
Answer
Each term is . If the sum is 0, every term is 0. The function is 0 on only at and . So every is 0 or 1, and since they sum to 1, exactly one is 1. - A model gives the probabilities to three classes. Compute the entropy of its
prediction in bits. Is the model confident?
Answer
bits, far below the maximum . The model is confident (whether it is also right is a different question).
What is the surprisal of an outcome with probability ?
; in bits, . A fair coin flip gives 1 bit, an outcome with gives 3 bits.
Why is surprisal defined with a logarithm?
For independent events, probabilities multiply but information should add. The log turns products into sums: .
Define the entropy of a discrete random variable .
: the average surprisal, with .
How do you convert an entropy from nats to bits?
Divide by (multiply by ). One bit is nats.
What is the entropy of a uniform distribution on outcomes?
; in bits, . This is the largest entropy any distribution on outcomes can have.
When is ?
Exactly when is constant: one value has probability 1.
Compute the entropy of in bits.
bits.
What is , and what is , in bits?
bit (the maximum); bits.
Why does the convention make sense?
as , and an outcome with probability 0 never happens, so it adds nothing to the average surprisal.
What does entropy have to do with yes/no questions?
It is the average number of yes/no questions needed to find the outcome with the best strategy, up to less than one extra question (exactly when all probabilities are powers of ).
9. Interview angle #
- "What is entropy, intuitively?" — The average surprise of the outcome, or the average number of yes/no questions needed to find it. Zero for a certain outcome, for equally likely outcomes.
- "Which distribution on outcomes has maximum entropy? Prove it." — The uniform one. Proof with (section 3), or with (lesson 03).
- "Your cross-entropy loss is 0.69. What does that mean?" — PyTorch uses nats, so this is bit per example: the model is as uncertain as a fair coin about the true label, on average.
- "How does the temperature of a language model change its outputs?" — The logits are divided by . A larger gives a flatter softmax with higher entropy (more diverse samples); a smaller gives a sharper one with lower entropy.
- "Why does a decision tree use entropy?" — The entropy of the labels at a node measures how mixed they are. A good split lowers the weighted entropy of the children (information gain).
10. Practice #
The notebook for this lesson runs in Colab. It has five exercises, each with a check cell and a folded solution:
- Write
surprisal(p, base)andentropy(p, base)with the convention , and check them againstscipy.stats.entropy. - Plot the binary entropy and find its maximum numerically.
- Compute the entropy of the letters of a short English text from their counts.
- Simulate the question game for and compare the average number of questions with .
- Compute the entropy of a softmax at several temperatures, and check that it grows with .
11. Watch and read #
- David MacKay, Information Theory, Inference, and Learning Algorithms, free PDF: §2.4 (definition of entropy and its bounds) and §4.1 (the information content of an outcome, the weighing problem).
- Kevin Murphy, Probabilistic Machine Learning: An Introduction, free PDF: §6.1.1 (entropy of discrete random variables).
- Claude Shannon, A Mathematical Theory of Communication (1948), §6: the definition of entropy and Theorem 2 on why its form is unique.
Runs in your browser with nothing to install. The notebook repeats the key demos and has exercises with checks; solutions are inside, folded.
No Google account needed: Python runs inside your browser. The first start downloads about 40 MB; your changes are saved in this browser only.