Module contents
Lesson 1 of 19Review 90 min

Shannon entropy: surprisal, uncertainty and the chain rule

A dense review of Shannon uncertainty, surprisal, entropy, units, axiomatic characterization and the extension to joint and conditional entropy and the chain rule. Entropy is interpreted as the minimum average number of yes/no questions, leading to compression and language-model loss.

After this lesson you can

  • Calculate discrete entropy in bits and nats and justify the bounds 0 ≤ H(X) ≤ log|X|.
  • Explain entropy as expected surprisal and as the minimum average number of binary questions.
  • Derive H(X,Y) = H(X) + H(Y|X) and apply it to joint tables and n variables.
  • Distinguish H(Y|X=x), which can exceed H(Y), from H(Y|X), which never does.
  • Implement vectorized, numerically safe entropy functions with the convention 0 log 0 = 0.

Before you start

Motivation: how many questions are needed?

Someone thinks of one of eight cards on a table and you must discover which by asking only yes/no questions. With eight equally likely cards, three questions suffice: the first rules out four, the second two and the third one. With a thousand cards, ten suffice (because 210=1024≥10002^{10} = 1024 \ge 1000). In the worst case each answer leaves at least half the possibilities, so identifying one among nn requires at least log⁡2n\log_2 n questions in the worst case.

Now change the rules: the cards are no longer equally likely. If one occurs half the time, asking “is it that one?” first succeeds immediately in half the games, and remaining questions are needed only when it fails. On average fewer questions are needed than under the uniform distribution, although the worst case may need more. This lesson asks how much fewer; the answer is one formula, Shannon entropy, with which Claude Shannon founded information theory in 1948.

This is the first chapter of a full module, and entropy appears throughout what follows:

  • Compression. If a random object is identified with HH questions on average, it can be written using HH bits on average. Entropy is the limit of lossless compression (lessons 4 to 7).
  • Loss functions. Cross-entropy minimized when training a classifier or language model is average surprise measured by the model and averaged over the true distribution (lesson 6). LM pretraining loss in nats per token has text entropy as its theoretical minimum.
  • ML tools. Decision-tree information gain, generative-model sampling temperature and reinforcement-learning entropy bonuses involve entropy or entropy differences under other names.
  • Choosing what to ask. A good Wordle strategy chooses the guess that divides remaining candidates as evenly as possible, maximizing expected answer information. Grant Sanderson (3Blue1Brown) develops this in detail in his video about the game.

The lesson builds the concept in order: event surprisal, its mean (entropy) and properties, its interpretation as average question count, an axiomatic justification for the formula, then pairs of variables with joint and conditional entropy and the chain rule. It ends with implementation and exercises.

Surprisal: why −log⁡p-\log p

An event that almost always happens is unsurprising; one that is nearly impossible is surprising. We want to quantify surprise as a function only of event probability p∈(0,1]p \in (0, 1], s(p)s(p). We ask for three reasonable properties:

  1. Continuity and monotonicity. ss is continuous and strictly decreasing: less likely means more surprising.
  2. Certainty. s(1)=0s(1) = 0: a certain event is not surprising.
  3. Additivity. For independent events, surprise that both occur is the sum of their surprises: s(pq)=s(p)+s(q)s(pq) = s(p) + s(q). Learning two unrelated things adds their surprises.

These conditions leave a unique function up to the unit of measurement.

Proof

Define f(t)=s(e−t)f(t) = s(e^{-t}) for t≥0t \ge 0. Then ff is continuous, strictly increasing and satisfies Cauchy’s equation f(t+u)=f(t)+f(u)f(t + u) = f(t) + f(u) because e−(t+u)=e−te−ue^{-(t+u)} = e^{-t}e^{-u}. From f(0)=2f(0)f(0) = 2f(0) follows f(0)=0f(0) = 0. By induction, f(nt)=nf(t)f(nt) = n f(t) for every integer n≥1n \ge 1; applying this to t/mt/m gives f(t/m)=f(t)/mf(t/m) = f(t)/m. Thus f(r)=rf(1)f(r) = r f(1) for every positive rational rr. Since ff is continuous and rationals are dense, f(t)=ctf(t) = ct with c=f(1)>0c = f(1) > 0 (positive because ff increases). Undoing the change gives s(p)=f(−ln⁡p)=−cln⁡ps(p) = f(-\ln p) = -c \ln p.

∎

Constant cc only chooses the unit. Writing c=1/ln⁡bc = 1/\ln b is equivalent to measuring with logarithms of base bb. This is the measure we use.

One bit is the surprisal of a fair coin outcome: −log⁡212=1-\log_2 \tfrac{1}{2} = 1. Drawing a specific card from a 52-card deck gives log⁡252≈5.70\log_2 52 \approx 5.70 bits. Conversion is a constant factor: 11 nat =log⁡2e≈1.4427= \log_2 e \approx 1.4427 bits, and 11 bit =ln⁡2≈0.6931= \ln 2 \approx 0.6931 nats. Theory and proofs use natural logarithms; compression and question counts use binary ones. When log⁡\log is written without a base, the formula holds for any base used consistently throughout.

Entropy: average surprisal

A random variable has a surprisal for each outcome rather than one surprisal. Naturally, we summarize them by their mean.

A couple of observations about the definition. First, entropy is a function only of mass pp: it does not depend on the values XX takes, only how probability is distributed among them. A variable taking {1,2,3}\{1, 2, 3\} with probabilities (0.5,0.3,0.2)(0.5, 0.3, 0.2) and another taking {−100,0,7}\{-100, 0, 7\} with the same probabilities have equal entropy and entirely different variances. Second, we write H⁡(X)\Ent(X) although it depends on pp; when distinction is needed, write H⁡(p)\Ent(p). For continuous variables with a density, the analogous formula is differential entropy, with different properties (it can be negative, for example); we study it in lesson 11.

A coin is the simplest case and already contains nearly everything.

InteractiveCoin surprisal and entropy
02468surprisal (bits)H = 0.722.320.32heads, p = 0.200tails, 1 − p = 0.800
  • heads: width pp, height −log⁡p-\log p
  • tails: width 1−p1-p, height −log⁡(1−p)-\log(1-p)
  • mean height =h2(p)=h_2(p)
  • tangent to h2h_2 at pp
0.200
Unit
Heads surprisal2.32 bits
Tails surprisal0.32 bits
Heads area, p(−log⁡p)p(-\log p)0.464
Tails area0.258
Entropy h2(p)h_2(p), sum of areas0.722 bits
Slope h2′(p)h_2'(p)2.00
Two heads in a row, −log⁡p2-\log p^24.64
Curve explored0 %
Each outcome is a bar whose width is its probability and whose height is its surprisal −log⁡p-\log p, so its area p (−log⁡p)p\,(-\log p) contributes to entropy. The total area, with width 1, is h2(p)h_2(p); the dashed line (average height) is therefore entropy. Start at p=0.2p = 0.2: tails, with probability 0.80.8, is unsurprising; heads is surprising but its bar is narrow. Move pp to 0.0050.005: what happens to the heads bar's area? Then press “Sweep the curve” and see where the tangent is horizontal and how steep it is at the endpoints. Change units and check that only the vertical scale changes.

The figure reveals three things hidden in the formula.

Rare outcomes are very surprising but carry little weight. With p=0.01p = 0.01, heads contributes 6.646.64 bits of surprisal, but occurs once in a hundred trials: its contribution to the mean, 0.01⋅6.64=0.0660.01 \cdot 6.64 = 0.066 bits, is tiny. This makes the limit tlog⁡t→0t \log t \to 0 visible, and so h2(0.01)=0.081h_2(0.01) = 0.081 bits. A coin that almost always lands tails is almost known in advance.

The mean is largest without a favorite. h2h_2 is symmetric about p=1/2p = 1/2, equals 11 bit there and is strictly concave. Its derivative, h2′(p)=log⁡21−pph_2'(p) = \log_2\frac{1 - p}{p}, vanishes at 1/21/2 and tends to ±∞\pm\infty at the endpoints: moving slightly away from certainty gains substantial uncertainty. Thus h2(0.11)≈0.5h_2(0.11) \approx 0.5 bits: a coin with 11 %11\,\% heads already has half the uncertainty of a fair one.

Additivity is visible. Two consecutive heads have probability p2p^2 and surprisal −log⁡p2=2(−log⁡p)-\log p^2 = 2(-\log p), as shown by the figure’s readout. The same holds for entropy: nn independent tosses have n h2(p)n\,h_2(p) bits of entropy, as the chain rule will show.

Three examples

Basic properties

Proof

(1) For 0<p(x)≤10 < p(x) \le 1 we have −log⁡p(x)≥0-\log p(x) \ge 0 and zero terms contribute nothing, so H⁡(X)≥0\Ent(X) \ge 0. The sum is zero only if every term p(x)log⁡1p(x)p(x)\log\frac{1}{p(x)} is zero, meaning each p(x)p(x) is 00 or 11: the mass is concentrated at one point.

(2) Write H⁡(X)=E[log⁡1p(X)]\Ent(X) = \E\big[\log\tfrac{1}{p(X)}\big]. Variable Z=1/p(X)Z = 1/p(X) is well defined with probability 1. Since log⁡\log is strictly concave, Jensen’s inequality gives

H⁡(X)=E[log⁡Z]≤log⁡E[Z]=log⁡∑x: p(x)>0p(x)1p(x)=log⁡∣supp⁡p∣≤log⁡n.\Ent(X) = \E[\log Z] \le \log \E[Z] = \log \sum_{x:\, p(x) > 0} p(x)\frac{1}{p(x)} = \log \abs{\operatorname{supp} p} \le \log n.

Equality in Jensen requires ZZ to be almost surely constant, meaning pp is constant on its support; the second inequality is equality if support is all of X\mathcal{X}. Together these mean pp is uniform.

(3) Function t↦−tlog⁡tt \mapsto -t\log t is concave on [0,1][0, 1] (with natural log⁡\log, its second derivative is −1/t<0-1/t < 0 on (0,1](0, 1]; another base only multiplies it by a positive constant), and H⁡(p)=∑x(−p(x)log⁡p(x))\Ent(p) = \sum_x (-p(x)\log p(x)) sums concave functions of each p(x)p(x). Symmetry follows because the sum ignores order, and adding p=0p = 0 adds 0log⁡0=00 \log 0 = 0. (4) is log⁡b=log⁡2/log⁡2b\log_b = \log_2 / \log_2 b.

∎

The upper bound has an immediate interpretation: greatest uncertainty over nn possibilities means no preference, costing log⁡n\log n questions. Any unequal distribution, however slight, reduces it. Concavity also says mixing two distributions never reduces entropy below the average of their entropies.

The question game

Now we can answer the opening question. A strategy for identifying XX with yes/no questions is a binary tree: each internal node is a question, each branch an answer and each leaf an outcome. The number of questions to reach outcome xx is its leaf depth d(x)d(x), and strategy cost is the mean L=∑xp(x) d(x)L = \sum_x p(x)\, d(x).

Two ideas guide construction. A question almost always answered the same way contributes little, because the answer was nearly known. Probable leaves should be near the root, so d(x)d(x) resembles surprisal −log⁡2p(x)-\log_2 p(x). With p=(1/2,1/4,1/8,1/8)p = (1/2, 1/4, 1/8, 1/8), depths 1,2,3,31, 2, 3, 3 match surprisals, giving L=H⁡(X)L = \Ent(X) exactly. When surprisals are not integers equality is impossible, and the question is how much is lost. The figure lets you try by hand.

InteractiveThe optimal-question game
0.34As = 1.60.22Bs = 2.20.16Cs = 2.60.10Ds = 3.30.07Es = 3.80.05Fs = 4.30.04Gs = 4.60.02Hs = 5.6YesNoYesNoYesNoYesNoYesNoYesNoYesNoP(node) = 1.00. P(yes) = 0.82. The answer gives 0.68 bits (maximum 1). Select to undo.0.68P(node) = 0.82. P(yes) = 0.68. The answer gives 0.90 bits (maximum 1). Select to undo.0.90P(node) = 0.56. P(yes) = 0.61. The answer gives 0.97 bits (maximum 1). Select to undo.0.97P(node) = 0.26. P(yes) = 0.62. The answer gives 0.96 bits (maximum 1). Select to undo.0.96P(node) = 0.18. P(yes) = 0.67. The answer gives 0.92 bits (maximum 1). Select to undo.0.92P(node) = 0.12. P(yes) = 0.58. The answer gives 0.98 bits (maximum 1). Select to undo.0.98P(node) = 0.06. P(yes) = 0.67. The answer gives 0.92 bits (maximum 1). Select to undo.0.92Ad = 3s = 1.6Bd = 3s = 2.2Cd = 3s = 2.6Dd = 3s = 3.3Ed = 3s = 3.8Fd = 3s = 4.3Gd = 3s = 4.6Hd = 3s = 5.6
  • node: bits from the answer, h2ge0.97h_2 \\ge 0.97
  • h2h_2 between 0.850.85 and 0.970.97
  • h2<0.85h_2 < 0.85: uneven split
  • branch width propto\\propto probability
  • leaf: dd questions, surprisal s=−log2ps=-\\log_2 p
Probability distribution
Build the tree
Entropy H(X)H(X)2.548 bits
Mean tree questions LL3.000
Excess L−HL - H0.452
Minimum possible L∗L^* (Huffman)2.610
Bits gained from the questions2.548 bits
The average is 0.3900.390 questions above the optimum. Red and yellow nodes mark questions that split probability unevenly.
Drag bars to distribute probability among eight objects (under each letter, ss is its surprisal in bits). The starting tree halves the number of objects: L=3L = 3 and H(X)=2.548H(X) = 2.548. Each node shows the bits contributed by its answer, h2h_2 of the ‘yes’ probability, and branch thickness shows probability flowing through it. Click a node to undo its question, then ask again by choosing objects answering ‘yes’. Try halving probability instead of object count: can you go below 2.5482.548? Compare with the optimal Huffman tree. With a dyadic distribution (powers of 1/21/2), achieve L=HL = H exactly; with ‘one favorite’, ask about it first.

Three facts visible when playing with default probabilities (H=2.548H = 2.548 bits):

  • Splitting eight objects into groups of four, two and one costs L=3L = 3 questions on average, nearly half a question above entropy and 0.390.39 above optimum: questions split object counts well but probability poorly.
  • Splitting probability as close to half as possible at each node lowers this to L=2.74L = 2.74. It is better but not optimal: always choosing the most balanced half is greedy and sometimes loses in the long run.
  • The optimal Huffman tree gives L∗=2.61L^* = 2.61. It lies above H=2.548H = 2.548 and below H+1H + 1, and this is no coincidence.

The two remaining facts are L≥H⁡(X)L \ge \Ent(X) for any tree, and that one can reach within one bit of HH. The first follows from the next section’s chain rule, showing that rule is not merely an artifice. The second is the source coding theorem, proved with Kraft’s inequality in lesson 5. The full result is

H⁡(X)  ≤  L∗  <  H⁡(X)+1,\Ent(X) \;\le\; L^* \;<\; \Ent(X) + 1,

so entropy is, within less than one question, the average number of questions in the best possible game.

Why this formula and no other

We have justified −log⁡p-\log p for surprisal, but why is average surprisal the right measure of a variable’s uncertainty? Shannon gave an axiomatic answer in 1948, refined by Khinchin in 1953. The idea is to ask the uncertainty H(p1,…,pn)H(p_1, \dots, p_n) to satisfy minimal reasonable requirements and show that its form is then determined.

Grouping says that uncertainty can be counted in two stages: first which block contains the outcome, then which element within that block. At heart this is the chain rule we will see shortly, and the theorem says this property, together with three technical conditions, already determines entropy. Faddeev (1956) showed that grouping two outcomes at a time suffices if HnH_n is also required to be symmetric.

ProofProof sketch

Let A(n)=Hn(1n,…,1n)A(n) = H_n(\tfrac{1}{n}, \dots, \tfrac{1}{n}). Grouping mnmn equiprobable outcomes into nn blocks of mm gives A(mn)=A(n)+A(m)A(mn) = A(n) + A(m); in particular, A(1)=0A(1) = 0 and A(ak)=k A(a)A(a^k) = k\,A(a). By expandability and maximality, A(n)=Hn+1(1n,…,1n,0)≤A(n+1)A(n) = H_{n+1}(\tfrac{1}{n}, \dots, \tfrac{1}{n}, 0) \le A(n + 1), so AA is nondecreasing. If A(2)=0A(2) = 0, AA vanishes on all powers of 22 and, by monotonicity, on every nn: this is the case c=0c = 0. Otherwise, A(a)≥A(2)>0A(a) \ge A(2) > 0 for every a≥2a \ge 2. Given integers a,b≥2a, b \ge 2 and k≥1k \ge 1, take mm with am≤bk<am+1a^m \le b^k < a^{m+1}. Monotonicity gives m A(a)≤k A(b)≤(m+1) A(a)m\,A(a) \le k\,A(b) \le (m + 1)\,A(a), and the same holds with log⁡\log instead of AA; hence A(b)/A(a)A(b)/A(a) and log⁡b/log⁡a\log b/\log a both lie in [m/k,(m+1)/k][m/k, (m+1)/k] and differ by at most 1/k1/k. Letting k→∞k \to \infty gives A(b)/log⁡b=A(a)/log⁡aA(b)/\log b = A(a)/\log a, that is, A(n)=clog⁡nA(n) = c\log n.

For rational probabilities pi=ni/Np_i = n_i/N, group NN equiprobable outcomes into blocks of sizes nin_i: grouping gives A(N)=H(p)+∑ipiA(ni)A(N) = H(p) + \sum_i p_i A(n_i). Rearranging,

H(p)=clog⁡N−c∑ipilog⁡ni=−c∑ipilog⁡niN=−c∑ipilog⁡pi.H(p) = c\log N - c\sum_i p_i \log n_i = -c\sum_i p_i \log\frac{n_i}{N} = -c\sum_i p_i\log p_i.

Continuity extends the formula from rational probabilities to all distributions.

∎

The conclusion is powerful. If uncertainty can be counted in stages and is continuous and maximal without preferences, Shannon entropy is the only choice up to the choice of unit. The chain rule’s place among the axioms hints at its central importance.

Joint and conditional entropy

For two variables XX and YY on the same probability space there are three natural entropies. The first is that of the pair viewed as one variable.

Nothing new: this is the entropy of the variable (X,Y)(X, Y) over the product alphabet. The second measures what remains to be learned about YY once XX is known. For a particular value xx with p(x)>0p(x) > 0, there is the conditional distribution p(y∣x)=p(x,y)/p(x)p(y \given x) = p(x, y)/p(x) and its entropy, H⁡(Y∣X=x)=−∑yp(y∣x)log⁡p(y∣x)\Ent(Y \given X = x) = -\sum_y p(y \given x)\log p(y \given x). Averaging over values of XX:

The equality of the three expressions follows in one line: substitute p(x,y)=p(x)p(y∣x)p(x, y) = p(x)p(y \given x) and rearrange the double sum. Notice that H⁡(Y∣X)\Ent(Y \given X) is a number, not a function of XX, because it has already been averaged; H⁡(Y∣X=x)\Ent(Y \given X = x) is different: a specific uncertainty for a specific value.

The chain rule

The natural question is how the three entropies are related. The answer is the most widely used identity in the module.

Proof

For every pair with p(x,y)>0p(x, y) > 0, we have p(x,y)=p(x) p(y∣x)p(x, y) = p(x)\,p(y \given x), the probability chain rule. Taking −log⁡-\log and expectations (the expectation is linear):

E[−log⁡p(X,Y)]=E[−log⁡p(X)]+E[−log⁡p(Y∣X)],\E[-\log p(X, Y)] = \E[-\log p(X)] + \E[-\log p(Y \given X)],

which is H⁡(X,Y)=H⁡(X)+H⁡(Y∣X)\Ent(X, Y) = \Ent(X) + \Ent(Y \given X). For nn variables, apply the two-variable case to the pair (X1,…,Xn−1)(X_1, \dots, X_{n-1}) and XnX_n: H⁡(X1,…,Xn)=H⁡(X1,…,Xn−1)+H⁡(Xn∣X1,…,Xn−1)\Ent(X_1, \dots, X_n) = \Ent(X_1, \dots, X_{n-1}) + \Ent(X_n \given X_1, \dots, X_{n-1}), and conclude by induction on nn.

∎

Entropy inherits the chain rule from probability because the logarithm turns products into sums. Each term is the new uncertainty contributed by variable ii once the preceding ones are known, and the sum is independent of their order because the left-hand side is. With two variables this gives two decompositions of the same number:

H⁡(X,Y)=H⁡(X)+H⁡(Y∣X)=H⁡(Y)+H⁡(X∣Y).\Ent(X, Y) = \Ent(X) + \Ent(Y \given X) = \Ent(Y) + \Ent(X \given Y).
InteractiveJoint table and the chain rule
y1y2y3y4H(Y)H(Y|X)x10.450.84x20.251.40x30.181.45x40.122.00 ▲p(x)H(Y | X = x) por fila, en bits0.380.040.020.010.030.170.030.020.020.020.120.020.030.030.030.030.460.260.200.08p(y)
01234bitsH(X) 1.83H(Y|X) 1.23H(Y) 1.78H(X|Y) 1.28H(X,Y) = 3.06X primeroY primero
  • H(X)H(X)
  • H(Y∣X)H(Y\mid X)
  • H(Y)H(Y)
  • H(X∣Y)H(X\mid Y)
  • row with H(YmidX=x)>H(Y)H(Y\\mid X{=}x) > H(Y) (▲)
H(X)H(X) (bits)1.831
H(Y∣X)H(Y\mid X)1.229
H(X)+H(Y∣X)H(X) + H(Y\mid X)3.059
H(Y)H(Y)1.777
H(X∣Y)H(X\mid Y)1.283
H(Y)+H(X∣Y)H(Y) + H(X\mid Y)3.059
H(X,Y)H(X,Y) from the table3.059
Reduction H(Y)−H(Y∣X)H(Y) - H(Y\mid X)0.548
Row x4x_4 has H(Y∣X=x)>H(Y)H(Y\mid X{=}x) > H(Y). Knowing this value of XX increases uncertainty about YY. The average still satisfies H(Y∣X)=1.23≤H(Y)=1.78H(Y\mid X) = 1.23 \le H(Y) = 1.78.
Edit a 4×44\times 4 joint table by dragging each cell upward (adding mass taken from the others) or downward. To the right of each row, H(Y∣X=x)H(Y \mid X{=}x) is compared with H(Y)H(Y) (dashed line) and its weighted mean H(Y∣X)H(Y \mid X) (solid line). Below, two stacked bars, one for each reading order, always measure H(X,Y)H(X,Y). Initially the unlikely, uniform row x4x_4 exceeds H(Y)H(Y): how can the average be lower? Try Independent (equal bars), Copy (H(Y∣X)=0H(Y\mid X) = 0), and Y=f(X)Y = f(X) (why is H(X∣Y)H(X\mid Y) not zero?). Drag mass into the rare row: the solid line moves, but never crosses the dashed line.

The order of the terms matters in the figure. If you read XX first, total uncertainty is what you do not know about XX plus what remains about YY once XX is known; reading YY first reverses this. The two stacked bars have the same height even though their segments differ. That difference between segments, H⁡(Y)−H⁡(Y∣X)=H⁡(X)−H⁡(X∣Y)\Ent(Y) - \Ent(Y \given X) = \Ent(X) - \Ent(X \given Y), is symmetric in XX and YY: the information each gives about the other, called mutual information in lesson 3.

Conditioning reduces entropy… on average

The figure shows something surprising. Learning something can leave you more confused: in the initial state, for x4x_4 we have H⁡(Y∣X=x4)=2\Ent(Y \given X = x_4) = 2 bits, whereas H⁡(Y)=1.78\Ent(Y) = 1.78 bits. This happens when a rare observation is followed by widely spread outcomes while the usual case is very concentrated. An extreme case: if with probability 0.90.9 we have Y=1Y = 1 and with probability 0.10.1 the value of YY is uniform over four possibilities, H⁡(Y)=0.50\Ent(Y) = 0.50 bits, but after observing the rare case uncertainty is 22 bits.

That does not contradict the following fundamental inequality of the module.

Proof

The chain rule makes the two inequalities equivalent. It suffices to show H⁡(Y∣X)−H⁡(Y)≤0\Ent(Y \given X) - \Ent(Y) \le 0:

H⁡(Y∣X)−H⁡(Y)=E[log⁡p(Y)p(Y∣X)]=E[log⁡p(X) p(Y)p(X,Y)]≤log⁡E[p(X) p(Y)p(X,Y)],\Ent(Y \given X) - \Ent(Y) = \E\Big[\log\frac{p(Y)}{p(Y \given X)}\Big] = \E\Big[\log\frac{p(X)\,p(Y)}{p(X, Y)}\Big] \le \log \E\Big[\frac{p(X)\,p(Y)}{p(X, Y)}\Big],

by Jensen’s inequality for the concave function log⁡\log. The expectation inside is ∑(x,y): p(x,y)>0p(x)p(y)≤∑x,yp(x)p(y)=1\sum_{(x, y):\, p(x, y) > 0} p(x)p(y) \le \sum_{x, y} p(x)p(y) = 1, so the right-hand side is at most log⁡1=0\log 1 = 0. Equality requires two things: the ratio p(x)p(y)/p(x,y)p(x)p(y)/p(x, y) must be constant on the support (equality in Jensen’s inequality), and its expectation must be 11, forcing the constant to be 11 and the support to be the whole product. That is, p(x,y)=p(x)p(y)p(x, y) = p(x)p(y).

∎

The difference between H⁡(Y∣X=x)\Ent(Y \given X = x) and H⁡(Y∣X)\Ent(Y \given X) is that between a particular case and the average: the inequality above compares the weighted average with H⁡(Y)\Ent(Y). A particular value of XX can leave you worse off, but averaging over its probability never does. This inequality is a special case of Gibbs’ inequality (Kullback–Leibler divergence is never negative), covered in lesson 2.

Other consequences of the chain rule you will use without thinking:

  • H⁡(X,Y)≥max⁡{H⁡(X),H⁡(Y)}\Ent(X, Y) \ge \max\{\Ent(X), \Ent(Y)\}, because H⁡(Y∣X)≥0\Ent(Y \given X) \ge 0.
  • If Y=f(X)Y = f(X) with deterministic ff, then H⁡(Y∣X)=0\Ent(Y \given X) = 0 and therefore H⁡(X,f(X))=H⁡(X)\Ent(X, f(X)) = \Ent(X). Applying the rule in the other order, H⁡(X,f(X))=H⁡(f(X))+H⁡(X∣f(X))\Ent(X, f(X)) = \Ent(f(X)) + \Ent(X \given f(X)), hence H⁡(f(X))=H⁡(X)−H⁡(X∣f(X))≤H⁡(X)\Ent(f(X)) = \Ent(X) - \Ent(X \given f(X)) \le \Ent(X): processing a variable does not create uncertainty and usually destroys it. Equality holds if and only if ff is injective on the support.
  • For independent variables, H⁡(X1,…,Xn)=∑iH⁡(Xi)\Ent(X_1, \dots, X_n) = \sum_i \Ent(X_i). In particular, nn independent coin flips have n h2(p)n\,h_2(p) bits.

Why no tree goes below HH

We can now settle the remaining question from the question game. The figure showed h2h_2 of the probability of “yes” at each node: this is no coincidence.

Proof

The depth of a leaf is the number of internal nodes traversed, so d(x)=∑v1[x pasa por v]d(x) = \sum_v \ind[x \text{ pasa por } v] and, taking expectations, L=E[d(X)]=∑vP(v)L = \E[d(X)] = \sum_v P(v). For entropy, let AkA_k be the answer to question number kk (with a constant value if the path has already ended). The answer sequence determines XX and XX determines the sequence, hence H⁡(X)=H⁡(A1,A2,… )\Ent(X) = \Ent(A_1, A_2, \dots). By the chain rule, H⁡(A1,A2,… )=∑kH⁡(Ak∣A<k)\Ent(A_1, A_2, \dots) = \sum_k \Ent(A_k \given A_{<k}). Given the path to a node vv, the answer is Bernoulli with parameter qvq_v and entropy h2(qv)h_2(q_v), and the path reaches vv with probability P(v)P(v); completed paths ask nothing and have entropy 0. Summing over kk gives H⁡(X)=∑vP(v)h2(qv)\Ent(X) = \sum_v P(v)h_2(q_v). The difference is nonnegative because h2≤1h_2 \le 1, and vanishes if and only if h2(qv)=1h_2(q_v) = 1, that is, qv=1/2q_v = 1/2, for every vv with P(v)>0P(v) > 0.

∎

The theorem gives the breakdown shown in the figure: the tree’s excess is the sum, node by node, of what each question wastes relative to one bit. It also shows why halving the number of objects fails: in the initial tree, the first question (“Is it among A, B, C and D?”) is answered yes with probability 0.820.82 and contributes only h2(0.82)=0.68h_2(0.82) = 0.68 bits; that always-visited node already wastes 0.320.32 questions out of the 0.450.45 excess. When all probabilities are powers of 1/21/2, every node can be made 50/50 and L=H⁡(X)L = \Ent(X). Conversely, if all nodes are 50/50, every leaf has probability 2−d(x)2^{-d(x)}; so as soon as any probability is not a power of 1/21/2, every tree has strictly positive excess, as you saw while playing.

Implementation from scratch

For tables, an entropy function must handle zeros. The classic trap is computing p * np.log(p) with p = 0: NumPy returns nan (because 0⋅(−∞)0 \cdot (-\infty) is undefined), contaminating everything. The solution is to apply the convention 0log⁡0=00 \log 0 = 0 explicitly, with a mask or scipy.special.xlogy. Here we use masks to see the mechanism, then check the three entropies against the chain rule.

[ ]Entropy, joint entropy and conditional entropyBrowser
import numpy as np
from scipy.stats import entropy as scipy_entropy

def entropy(p, base=2.0):
    """Entropía de un vector de probabilidades, con 0 log 0 = 0."""
    p = np.asarray(p, dtype=float).ravel()
    p = p[p > 0]                                   # los ceros aportan 0: se descartan
    return float(-(p * np.log(p)).sum() / np.log(base))

def joint_entropy(pxy, base=2.0):
    return entropy(pxy, base)                      # la tabla entera es una sola distribución

def conditional_entropy(pxy, base=2.0):
    """H(Y|X) con las filas de pxy indexadas por x y las columnas por y: H(X,Y) - H(X)."""
    pxy = np.asarray(pxy, dtype=float)
    return joint_entropy(pxy, base) - entropy(pxy.sum(axis=1), base)

# la trampa de los ceros
p = np.array([0.5, 0.5, 0.0])
with np.errstate(all="ignore"):
    ingenuo = -(p * np.log2(p)).sum()
print("sin proteger: ", ingenuo, "   protegida:", entropy(p))

# validación contra scipy (que devuelve nats por defecto)
rng = np.random.default_rng(0)
q = rng.dirichlet(np.ones(6))
print("H(q) bits:", round(entropy(q), 6), "  scipy:", round(float(scipy_entropy(q, base=2)), 6),
      "  nats:", round(entropy(q, np.e), 6), "  scipy:", round(float(scipy_entropy(q)), 6))
print("máximo log2 6 =", round(np.log2(6), 6), "   uniforme:", round(entropy(np.ones(6) / 6), 6))

# regla de la cadena y desigualdades en tablas aleatorias 4x4
errores, rompe = [], 0
for _ in range(1000):
    t = rng.dirichlet(np.ones(16) * 0.3).reshape(4, 4)
    HX, HY = entropy(t.sum(1)), entropy(t.sum(0))
    HYgX, HXgY = conditional_entropy(t), conditional_entropy(t.T)
    errores.append(abs(joint_entropy(t) - HX - HYgX))
    errores.append(abs(joint_entropy(t) - HY - HXgY))
    rompe += (HYgX > HY + 1e-12) + (joint_entropy(t) > HX + HY + 1e-12)
print("error máximo de la regla de la cadena:", f"{max(errores):.1e}", "   violaciones de H(Y|X) <= H(Y):", rompe)

# la tabla de la figura (lluvia y paraguas) y la del ejercicio
t = np.array([[0.27, 0.03], [0.14, 0.56]])
print("lluvia/paraguas: H(Y) =", round(entropy(t.sum(0)), 3), "  H(Y|X) =", round(conditional_entropy(t), 3))
raro = np.zeros((2, 4)); raro[0, 0] = 0.9; raro[1, :] = 0.025
print("caso raro: H(Y) =", round(entropy(raro.sum(0)), 3), "  H(Y|X=raro) =", round(entropy(raro[1] / raro[1].sum()), 3), "  H(Y|X) =", round(conditional_entropy(raro), 3))

Everything checks out: the masked version agrees with SciPy to six decimal places in bits and nats, the chain rule holds up to rounding error for a thousand random tables, and H(Y|X) <= H(Y) is never violated, even though individual rows exceed it (the rare case in the text: 0.500.50 bits versus 22 bits for the rare row, with an average of 0.20.2).

The entropy of Spanish letters

Let us move from invented tables to data. We take the first paragraph of Don Quixote (public domain), normalize it to an alphabet of 28 symbols (the 26 letters of the English alphabet, ñ, and space), and estimate the entropy of a letter, that of letter pairs, and the conditional entropy of a letter given its predecessor using the text’s frequencies (plug-in estimation).

[ ]Entropy of Spanish lettersBrowser
import numpy as np, unicodedata, re

TEXTO = """En un lugar de la Mancha, de cuyo nombre no quiero acordarme, no ha mucho tiempo que vivía un hidalgo de los de lanza en astillero, adarga antigua, rocín flaco y galgo corredor. Una olla de algo más vaca que carnero, salpicón las más noches, duelos y quebrantos los sábados, lentejas los viernes, algún palomino de añadidura los domingos, consumían las tres partes de su hacienda. El resto della concluían sayo de velarte, calzas de velludo para las fiestas con sus pantuflos de lo mismo, y los días de entre semana se honraba con su vellorí de lo más fino. Tenía en su casa una ama que pasaba de los cuarenta, y una sobrina que no llegaba a los veinte, y un mozo de campo y plaza, que así ensillaba el rocín como tomaba la podadera. Frisaba la edad de nuestro hidalgo con los cincuenta años; era de complexión recia, seco de carnes, enjuto de rostro, gran madrugador y amigo de la caza. Quieren decir que tenía el sobrenombre de Quijada, o Quesada, que en esto hay alguna diferencia en los autores que deste caso escriben, aunque por conjeturas verosímiles se deja entender que se llama Quijana. Pero esto importa poco a nuestro cuento; basta que en la narración dél no se salga un punto de la verdad."""

ALFABETO = "abcdefghijklmnopqrstuvwxyzñ "
def limpiar(s):
    s = s.lower().replace("ñ", "\0")                          # protege la ñ de la descomposición
    s = "".join(c for c in unicodedata.normalize("NFD", s) if not unicodedata.combining(c))
    s = s.replace("\0", "ñ")
    s = re.sub(r"[^a-zñ ]", " ", s)
    return re.sub(r" +", " ", s).strip()

def H(p):
    p = np.asarray(p, dtype=float).ravel()
    p = p[p > 0]
    return float(-(p * np.log2(p)).sum())

x = np.array([ALFABETO.index(c) for c in limpiar(TEXTO)])
n = len(ALFABETO)
p1 = np.bincount(x, minlength=n) / len(x)
J = np.zeros((n, n)); np.add.at(J, (x[:-1], x[1:]), 1); J /= J.sum()   # frecuencias de pares consecutivos

H1 = H(p1)
H2c = H(J) - H(J.sum(axis=1))                                          # H(X2 | X1) = H(X1, X2) - H(X1)
print(f"letras: {len(x)}   alfabeto: {n} símbolos")
print(f"cota uniforme log2({n}) = {np.log2(n):.3f} bits   H(letra) = {H1:.3f} bits")
print(f"H(par) = {H(J):.3f}   H(X2|X1) por sustitución = {H2c:.3f} bits")
orden = np.argsort(-p1)[:6]
print("más frecuentes:", ", ".join(f"{ALFABETO[i]!r}:{p1[i]:.3f}" for i in orden))

# ¿cuánto de esa bajada es real? Barajando el texto los pares son independientes y H(X2|X1) debería valer H(X1)
rng = np.random.default_rng(0)
sinteticos = []
for _ in range(20):
    y = rng.permutation(x)
    K = np.zeros((n, n)); np.add.at(K, (y[:-1], y[1:]), 1); K /= K.sum()
    sinteticos.append(H(K) - H(K.sum(axis=1)))
sesgo = H1 - np.mean(sinteticos)
print(f"texto barajado: H(X2|X1) por sustitución = {np.mean(sinteticos):.3f} (verdad: {H1:.3f})  sesgo hacia abajo ≈ {sesgo:.2f} bits")
print(f"estimación corregida por ese sesgo (orden de magnitud): {H2c + sesgo:.2f} bits")

There are two lessons. The first is expected: the entropy of a letter, about 44 bits, is clearly below log⁡228=4.81\log_2 28 = 4.81 because letters are not equiprobable (space, “a” and “e” dominate). Knowing the preceding letter reduces uncertainty much further (the plug-in estimate gives 2.832.83 bits), because Spanish has structure. The second is a methodological warning: the conditional plug-in estimate is biased downward with so little data. The shuffled text, whose true conditional entropy equals that of a single letter, gives an estimate about three tenths of a bit lower (0.320.32 in the output above); adjusting for this bias puts the conditional entropy around 3.153.15 bits. With 1 1731\,173 letters and 784784 possible pairs, the pair table is too sparse to trust. How to estimate entropy from finite data without misleading yourself is the subject of plug-in estimation in lesson 17; for now, interpret the conditional figure as an order-of-magnitude bound.

The version using libraries

In practice you will use SciPy and PyTorch routines. scipy.stats.entropy(pk, base=2) normalizes the vector and applies the zero convention, and scipy.special.entr(x) computes −xln⁡x-x\ln x element by element with 0↦00 \mapsto 0. In PyTorch, the categorical distribution includes its entropy and handles logits stably, always in nats:

import torch
from torch.distributions import Categorical

logits = torch.tensor([2.0, 1.0, 0.5, 0.0, -1.0])
H_nats = Categorical(logits=logits).entropy()          # en nats
H_bits = H_nats / torch.log(torch.tensor(2.0))

An immediate application is sampling temperature. Dividing logits by TT before softmax moves the entropy of a model’s output distribution from 00 (with T→0T \to 0, the greedy decision) to log⁡n\log n (with T→∞T \to \infty, the uniform distribution):

[ ]Temperature controls entropyBrowser
import numpy as np
import matplotlib.pyplot as plt
from scipy.special import softmax
from scipy.stats import entropy

z = np.array([2.0, 1.0, 0.5, 0.0, -1.0])
for T in (0.1, 0.5, 1.0, 2.0, 5.0, 50.0):
    q = softmax(z / T)
    print(f"T = {T:5.1f}   H = {entropy(q):.3f} nats = {entropy(q, base=2):.3f} bits   p máxima = {q.max():.3f}")
print(f"tope log(5) = {np.log(5):.3f} nats")

Ts = np.logspace(-1.3, 2, 200)
plt.semilogx(Ts, [entropy(softmax(z / T)) for T in Ts], label="H(softmax(z/T))")
plt.axhline(np.log(len(z)), color="gray", linestyle="--", label="log n")
plt.xlabel("temperatura T"); plt.ylabel("entropía (nats)"); plt.legend(); plt.show()

The curve increases from 00 to ln⁡5=1.609\ln 5 = 1.609 nats. At T=1T = 1 it is 1.2061.206 nats; at T=0.1T = 0.1 it is nearly zero (the model always chooses the same thing), and at T=50T = 50 nearly ln⁡5\ln 5 (every option is equally good). This is the same idea of entropy as uncertainty, now about a model’s next word.

Connections

  • Language models. The probability of a text of TT tokens factorizes as p(x1,…,xT)=∏tp(xt∣x<t)p(x_1, \dots, x_T) = \prod_t p(x_t \given x_{<t}), and the entropy chain rule is its averaged logarithm. An autoregressive model learns each factor separately, and the per-token loss it minimizes is a cross-entropy (lesson 6) whose floor is the conditional entropy of each token given its context.
  • Decision trees. The information gain used to choose a split is a reduction in conditional entropy: H⁡(Y)−H⁡(Y∣divisioˊn)\Ent(Y) - \Ent(Y \given \text{división}). With 14 examples, 9 positive and 5 negative, H⁡(Y)=0.940\Ent(Y) = 0.940 bits; a variable that divides them into (6,2)(6, 2) and (3,3)(3, 3) leaves 814⋅0.811+614⋅1=0.892\tfrac{8}{14}\cdot 0.811 + \tfrac{6}{14}\cdot 1 = 0.892 bits and gains only 0.0480.048 bits. We will see this in the decision tree section on supervised ML.
  • Sampling and temperature. Controlling sampling temperature controls the entropy of the output distribution, as we have seen.
  • Reinforcement learning. Maximum-entropy methods such as SAC add a term proportional to policy entropy to the reward, encouraging exploration.

Common mistakes

Exercises

NumericA dyadic distribution
Calculate the entropy in bits of the distribution (1/2,1/4,1/8,1/8)(1/2, 1/4, 1/8, 1/8).
NumericA conditional entropy
For the joint table p(0,0)=1/2p(0, 0) = 1/2, p(0,1)=1/4p(0, 1) = 1/4, p(1,0)=0p(1, 0) = 0, p(1,1)=1/4p(1, 1) = 1/4 (first index xx, second yy), calculate H⁡(Y∣X)\Ent(Y \given X) in bits.
NumericEntropy of a geometric distribution
The number of tosses until the first head of a coin with P(heads)=1/4\Pr(\text{heads}) = 1/4 has a geometric distribution on {1,2,… }\{1, 2, \dots\}. Calculate its entropy in bits.
NumericInformation gain in a tree
A node has 14 examples, 9 positive and 5 negative. A binary variable divides them into a group of 8 with 6 positive and 2 negative, and a group of 6 with 3 positive and 3 negative. Calculate the information gain (entropy reduction in bits).
NumericFrom nats to bits
A language model has entropy 1.51.5 nats per token on a certain text. How many bits per token is this?
NumericHow informative is a question?
An object is A with probability 0.90.9. How many bits of information does the answer to “Is it A?” provide on average?
QuizThe best first question
Five objects A, B, C, D and E have probabilities (0.5,0.2,0.1,0.1,0.1)(0.5, 0.2, 0.1, 0.1, 0.1). What is the best first question?
QuizEntropy of a function of X
Let Y=f(X)Y = f(X) with deterministic ff. What is the relationship between H⁡(Y)\Ent(Y) and H⁡(X)\Ent(X)?
QuizWhat is true of conditional entropy?
Which statements are true for discrete random variables XX and YY with finite entropy?

More than one answer may be correct.

ProofThe entropy chain rule
Prove: For discrete random variables X1,…,XnX_1, \dots, X_n, H⁡(X1,…,Xn)=∑i=1nH⁡(Xi∣X1,…,Xi−1)\Ent(X_1, \dots, X_n) = \sum_{i=1}^{n}\Ent(X_i \given X_1, \dots, X_{i-1}).
0
Start with two variables, H⁡(X,Y)=H⁡(X)+H⁡(Y∣X)\Ent(X, Y) = \Ent(X) + \Ent(Y \given X), and generalize by induction.

Step 1 of 4. Which probability identity is your starting point?

ProofEntropy does not exceed log n
Prove: If XX takes nn values, H⁡(X)≤log⁡n\Ent(X) \le \log n, with equality if and only if XX is uniform.
0
Use Jensen's inequality for the concave function log⁡\log.

Step 1 of 4. How do you write H⁡(X)\Ent(X) so you can apply Jensen?

CodeRobust conditional entropy
Implement conditional_entropy(pxy, base=2.0), accepting a joint table pxy (rows indexed by xx, columns by yy, summing to 1) and returning H⁡(Y∣X)\Ent(Y \given X) in the specified base. It must handle zeros in the table, entire zero rows and columns, and degenerate one-cell tables without nan, using only the definition: H⁡(Y∣X)=−∑x,yp(x,y)log⁡p(y∣x)\Ent(Y \given X) = -\sum_{x, y} p(x, y)\log p(y \given x) with p(y∣x)=p(x,y)/p(x)p(y \given x) = p(x, y)/p(x).
import numpy as np

def conditional_entropy(pxy, base=2.0):
  """H(Y|X) en la base dada, con pxy[x, y] = p(x, y)."""
  pxy = np.asarray(pxy, dtype=float)
  px = pxy.sum(axis=1, keepdims=True)
  cond = pxy / px
  return float(-(pxy * np.log(cond)).sum() / np.log(base))
Shift+Enter to run

Summary

Key idea
Entropy H⁡(X)=−∑xp(x)log⁡p(x)\Ent(X) = -\sum_x p(x)\log p(x) is the average surprisal of XX: the average number of yes/no questions needed to identify it, to within less than one question. With several variables, the chain rule H⁡(X,Y)=H⁡(X)+H⁡(Y∣X)\Ent(X, Y) = \Ent(X) + \Ent(Y \given X) divides uncertainty into increments, and conditioning always reduces it on average, though not necessarily in every case.
  • Surprisal −log⁡p-\log p is the only continuous, decreasing measure additive for independent events (up to units: bits with log⁡2\log_2, nats with ln⁡\ln, and 11 nat =1.4427= 1.4427 bits).
  • 0≤H⁡(X)≤log⁡n0 \le \Ent(X) \le \log n. The minimum, 00, is certainty; the maximum, log⁡n\log n, occurs only for the uniform distribution. Entropy depends only on probabilities, not on the values taken by XX.
  • h2(p)h_2(p) is concave, symmetric, maximal (11 bit) at 1/21/2, with infinite slope at the endpoints: rare outcomes are very surprising but carry little weight.
  • Every question tree takes L=H⁡(X)+∑vP(v)(1−h2(qv))≥H⁡(X)L = \Ent(X) + \sum_v P(v)(1 - h_2(q_v)) \ge \Ent(X); entropy is attained only if each question halves the probability, and the optimal tree satisfies H⁡(X)≤L∗<H⁡(X)+1\Ent(X) \le L^* < \Ent(X) + 1.
  • Shannon and Khinchin: continuity, maximum at the uniform distribution, expandability and grouping (the chain rule) determine entropy up to a constant.
  • H⁡(X,Y)=H⁡(X)+H⁡(Y∣X)=H⁡(Y)+H⁡(X∣Y)\Ent(X, Y) = \Ent(X) + \Ent(Y \given X) = \Ent(Y) + \Ent(X \given Y), and by induction H⁡(X1,…,Xn)=∑iH⁡(Xi∣X<i)\Ent(X_1, \dots, X_n) = \sum_i \Ent(X_i \given X_{<i}).
  • H⁡(Y∣X=x)\Ent(Y \given X = x) can exceed H⁡(Y)\Ent(Y); the average H⁡(Y∣X)\Ent(Y \given X) cannot. With Y=f(X)Y = f(X), H⁡(f(X))≤H⁡(X)\Ent(f(X)) \le \Ent(X).
  • In code, apply 0log⁡0=00 \log 0 = 0 with masks or scipy.special.xlogy, and remember PyTorch and SciPy use nats by default.