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 ). In the worst case each answer leaves at least half the possibilities, so identifying one among requires at least 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 questions on average, it can be written using 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
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 , . We ask for three reasonable properties:
- Continuity and monotonicity. is continuous and strictly decreasing: less likely means more surprising.
- Certainty. : a certain event is not surprising.
- Additivity. For independent events, surprise that both occur is the sum of their surprises: . Learning two unrelated things adds their surprises.
These conditions leave a unique function up to the unit of measurement.
Proof
Define for . Then is continuous, strictly increasing and satisfies Cauchy’s equation because . From follows . By induction, for every integer ; applying this to gives . Thus for every positive rational . Since is continuous and rationals are dense, with (positive because increases). Undoing the change gives .
∎Constant only chooses the unit. Writing is equivalent to measuring with logarithms of base . This is the measure we use.
One bit is the surprisal of a fair coin outcome: . Drawing a specific card from a 52-card deck gives bits. Conversion is a constant factor: nat bits, and bit nats. Theory and proofs use natural logarithms; compression and question counts use binary ones. When 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 : it does not depend on the values takes, only how probability is distributed among them. A variable taking with probabilities and another taking with the same probabilities have equal entropy and entirely different variances. Second, we write although it depends on ; when distinction is needed, write . 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.
The figure reveals three things hidden in the formula.
Rare outcomes are very surprising but carry little weight. With , heads contributes bits of surprisal, but occurs once in a hundred trials: its contribution to the mean, bits, is tiny. This makes the limit visible, and so bits. A coin that almost always lands tails is almost known in advance.
The mean is largest without a favorite. is symmetric about , equals bit there and is strictly concave. Its derivative, , vanishes at and tends to at the endpoints: moving slightly away from certainty gains substantial uncertainty. Thus bits: a coin with heads already has half the uncertainty of a fair one.
Additivity is visible. Two consecutive heads have probability and surprisal , as shown by the figure’s readout. The same holds for entropy: independent tosses have bits of entropy, as the chain rule will show.
Three examples
Basic properties
Proof
(1) For we have and zero terms contribute nothing, so . The sum is zero only if every term is zero, meaning each is or : the mass is concentrated at one point.
(2) Write . Variable is well defined with probability 1. Since is strictly concave, Jensen’s inequality gives
Equality in Jensen requires to be almost surely constant, meaning is constant on its support; the second inequality is equality if support is all of . Together these mean is uniform.
(3) Function is concave on (with natural , its second derivative is on ; another base only multiplies it by a positive constant), and sums concave functions of each . Symmetry follows because the sum ignores order, and adding adds . (4) is .
∎The upper bound has an immediate interpretation: greatest uncertainty over possibilities means no preference, costing 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 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 is its leaf depth , and strategy cost is the mean .
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 resembles surprisal . With , depths match surprisals, giving exactly. When surprisals are not integers equality is impossible, and the question is how much is lost. The figure lets you try by hand.
Three facts visible when playing with default probabilities ( bits):
- Splitting eight objects into groups of four, two and one costs questions on average, nearly half a question above entropy and above optimum: questions split object counts well but probability poorly.
- Splitting probability as close to half as possible at each node lowers this to . 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 . It lies above and below , and this is no coincidence.
The two remaining facts are for any tree, and that one can reach within one bit of . 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
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 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 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 is also required to be symmetric.
ProofProof sketch
Let . Grouping equiprobable outcomes into blocks of gives ; in particular, and . By expandability and maximality, , so is nondecreasing. If , vanishes on all powers of and, by monotonicity, on every : this is the case . Otherwise, for every . Given integers and , take with . Monotonicity gives , and the same holds with instead of ; hence and both lie in and differ by at most . Letting gives , that is, .
For rational probabilities , group equiprobable outcomes into blocks of sizes : grouping gives . Rearranging,
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 and 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 over the product alphabet. The second measures what remains to be learned about once is known. For a particular value with , there is the conditional distribution and its entropy, . Averaging over values of :
The equality of the three expressions follows in one line: substitute and rearrange the double sum. Notice that is a number, not a function of , because it has already been averaged; 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 , we have , the probability chain rule. Taking and expectations (the expectation is linear):
which is . For variables, apply the two-variable case to the pair and : , and conclude by induction on .
∎Entropy inherits the chain rule from probability because the logarithm turns products into sums. Each term is the new uncertainty contributed by variable 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:
The order of the terms matters in the figure. If you read first, total uncertainty is what you do not know about plus what remains about once is known; reading first reverses this. The two stacked bars have the same height even though their segments differ. That difference between segments, , is symmetric in and : 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 we have bits, whereas 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 we have and with probability the value of is uniform over four possibilities, bits, but after observing the rare case uncertainty is 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 :
by Jensen’s inequality for the concave function . The expectation inside is , so the right-hand side is at most . Equality requires two things: the ratio must be constant on the support (equality in Jensen’s inequality), and its expectation must be , forcing the constant to be and the support to be the whole product. That is, .
∎The difference between and is that between a particular case and the average: the inequality above compares the weighted average with . A particular value of 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:
- , because .
- If with deterministic , then and therefore . Applying the rule in the other order, , hence : processing a variable does not create uncertainty and usually destroys it. Equality holds if and only if is injective on the support.
- For independent variables, . In particular, independent coin flips have bits.
Why no tree goes below
We can now settle the remaining question from the question game. The figure showed 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 and, taking expectations, . For entropy, let be the answer to question number (with a constant value if the path has already ended). The answer sequence determines and determines the sequence, hence . By the chain rule, . Given the path to a node , the answer is Bernoulli with parameter and entropy , and the path reaches with probability ; completed paths ask nothing and have entropy 0. Summing over gives . The difference is nonnegative because , and vanishes if and only if , that is, , for every with .
∎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 and contributes only bits; that always-visited node already wastes questions out of the excess. When all probabilities are powers of , every node can be made 50/50 and . Conversely, if all nodes are 50/50, every leaf has probability ; so as soon as any probability is not a power of , 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 is undefined), contaminating everything. The solution is to apply the convention 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.
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: bits versus bits for the rare row, with an average of ).
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).
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 bits, is clearly below because letters are not equiprobable (space, “a” and “e” dominate). Knowing the preceding letter reduces uncertainty much further (the plug-in estimate gives 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 ( in the output above); adjusting for this bias puts the conditional entropy around bits. With letters and 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 element by element with . 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 before softmax moves the entropy of a model’s output distribution from (with , the greedy decision) to (with , the uniform distribution):
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 to nats. At it is nats; at it is nearly zero (the model always chooses the same thing), and at nearly (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 tokens factorizes as , 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: . With 14 examples, 9 positive and 5 negative, bits; a variable that divides them into and leaves bits and gains only 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
More than one answer may be correct.
Step 1 of 4. Which probability identity is your starting point?
Step 1 of 4. How do you write so you can apply Jensen?
conditional_entropy(pxy, base=2.0), accepting a joint table pxy (rows indexed by , columns by , summing to 1) and returning 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: with .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))Summary
- Surprisal is the only continuous, decreasing measure additive for independent events (up to units: bits with , nats with , and nat bits).
- . The minimum, , is certainty; the maximum, , occurs only for the uniform distribution. Entropy depends only on probabilities, not on the values taken by .
- is concave, symmetric, maximal ( bit) at , with infinite slope at the endpoints: rare outcomes are very surprising but carry little weight.
- Every question tree takes ; entropy is attained only if each question halves the probability, and the optimal tree satisfies .
- Shannon and Khinchin: continuity, maximum at the uniform distribution, expandability and grouping (the chain rule) determine entropy up to a constant.
- , and by induction .
- can exceed ; the average cannot. With , .
- In code, apply with masks or
scipy.special.xlogy, and remember PyTorch and SciPy use nats by default.