Skip to content
LeetQuant
E03 Information Theory

E03 · Information Theory · Lesson 1 of 4

Entropy

Shannon entropy as the average number of yes/no questions needed to pin down an outcome: its definition, maximum-entropy distributions, joint and conditional entropy, Huffman codes, cross-entropy and KL divergence.

18 min

Objective

Be able to compute the entropy of a discrete distribution, explain what it measures, build a Huffman code and use cross-entropy and KL divergence to measure the cost of a wrong model. These are the tools the rest of the module is built on.

Intuition: surprise, averaged

An outcome with probability pp carries −log⁡2p-\log_2 p bits of surprise. A fair coin landing heads: 1 bit. A specific card from a shuffled deck: log⁡252≈5.7\log_2 52 \approx 5.7 bits. Something certain: 0 bits. Rare events are surprising, and independent surprises add because their probabilities multiply.

Entropy is the expected surprise:

H(X)=−∑xp(x)log⁡2p(x)=E[−log⁡2p(X)],H(X) = -\sum_x p(x)\log_2 p(x) = E\left[-\log_2 p(X)\right],

with 0log⁡0=00 \log 0 = 0. Read it as "the average number of well-chosen yes/no questions needed to learn XX". With natural logs the unit is the nat; 1 nat=1/ln⁡2≈1.4431 \text{ nat} = 1/\ln 2 \approx 1.443 bits.

DistributionEntropy (bits)
Fair coin1
Coin with P(H)=0.9P(H) = 0.90.4690.469
Fair dielog⁡26≈2.585\log_2 6 \approx 2.585
Sum of two dice3.2743.274
Uniform on nn outcomeslog⁡2n\log_2 n

The binary entropy function h(p)=−plog⁡2p−(1−p)log⁡2(1−p)h(p) = -p\log_2 p - (1-p)\log_2(1-p) is symmetric about 12\tfrac12, peaks at 1 bit there and falls to 0 at p∈{0,1}p \in \{0, 1\}. It appears constantly, so it is worth remembering h(0.75)≈0.811h(0.75) \approx 0.811 and h(0.9)≈0.469h(0.9) \approx 0.469.

Maximum entropy

Entropy is a measure of spread, so the natural question is which distribution is most spread out under a given constraint.

  • Finite support of size nn: the uniform distribution, with H=log⁡2nH = \log_2 n. Every other distribution has strictly less (proof below via KL divergence).
  • Support {0,1,2,… }\{0, 1, 2, \dots\} with a fixed mean: the geometric distribution.
  • Support [0,∞)[0, \infty) with a fixed mean: the exponential distribution (for continuous variables, using differential entropy −∫flog⁡f-\int f \log f).
  • The real line with a fixed variance σ2\sigma^2: the normal distribution, with differential entropy 12log⁡2(2πeσ2)\tfrac12\log_2(2\pi e\sigma^2) bits.

In general, maximising entropy subject to E[Tk(X)]=ckE[T_k(X)] = c_k gives p(x)∝exp⁡(∑kλkTk(x))p(x) \propto \exp\left(\sum_k \lambda_k T_k(x)\right), an exponential family. This is why "assume the normal distribution" is the least-committal choice when you only know a mean and a variance.

Joint and conditional entropy

For a pair (X,Y)(X, Y), the joint entropy is H(X,Y)=−∑x,yp(x,y)log⁡2p(x,y)H(X, Y) = -\sum_{x,y} p(x,y)\log_2 p(x,y). The conditional entropy averages the entropy left in YY after seeing XX:

H(Y∣X)=∑xp(x) H(Y∣X=x).H(Y \mid X) = \sum_x p(x)\, H(Y \mid X = x) .

The chain rule says learning the pair is learning XX and then YY given XX:

H(X,Y)=H(X)+H(Y∣X),H(X1,…,Xn)=∑iH(Xi∣X1,…,Xi−1).H(X, Y) = H(X) + H(Y \mid X), \qquad H(X_1,\dots,X_n) = \sum_{i} H(X_i \mid X_1,\dots,X_{i-1}).

Two consequences: H(Y∣X)≤H(Y)H(Y \mid X) \le H(Y) (conditioning cannot increase entropy on average), and H(X,Y)≤H(X)+H(Y)H(X, Y) \le H(X) + H(Y) with equality exactly when XX and YY are independent.

Example: roll a fair die, XX the face and YY its parity. YY is a function of XX, so H(X,Y)=H(X)=log⁡26H(X, Y) = H(X) = \log_2 6. The other order gives H(Y)+H(X∣Y)=1+log⁡23=log⁡26H(Y) + H(X \mid Y) = 1 + \log_2 3 = \log_2 6, as it must: once you know the parity, three faces remain.

Source coding: why entropy counts bits

A prefix code assigns each symbol a binary codeword so that no codeword is a prefix of another; a stream of codewords can then be decoded without separators. Codeword lengths ℓx\ell_x are achievable by a prefix code if and only if they satisfy the Kraft inequality ∑x2−ℓx≤1\sum_x 2^{-\ell_x} \le 1.

Source coding theorem. Every prefix code has expected length L=∑xp(x)ℓx≥H(X)L = \sum_x p(x)\ell_x \ge H(X), and the best one has L<H(X)+1L < H(X) + 1. Coding blocks of nn symbols at once brings the per-symbol cost within 1/n1/n of HH.

The lower bound is a one-line consequence of the next section: with q(x)=2−ℓx/∑2−ℓq(x) = 2^{-\ell_x}/\sum 2^{-\ell}, L−H=D(p ∥ q)−log⁡2∑2−ℓ≥0L - H = D(p \,\|\, q) - \log_2\sum 2^{-\ell} \ge 0. The ideal length of symbol xx is −log⁡2p(x)-\log_2 p(x), exactly its surprise.

A prefix code is also a questioning strategy: the first bit answers "is the symbol in the left half of the tree?", and so on. So H(X)H(X) is a lower bound on the expected number of yes/no questions needed to identify XX, and the optimal code is the optimal strategy.

Huffman's algorithm

Huffman coding builds an optimal prefix code greedily: repeatedly merge the two least likely symbols (or merged groups) into one node whose probability is their sum, until one node remains. Each merge adds one bit to every symbol inside the two merged nodes.

Worked example

a Huffman code

A source emits A, B, C, D, E with probabilities 0.4,0.3,0.15,0.1,0.050.4, 0.3, 0.15, 0.1, 0.05. Build a Huffman code, find its expected length and compare it with the entropy and with a fixed-length code.

Show solution

Merges (always the two smallest):

  1. D (0.10) + E (0.05) → DE (0.15).
  2. C (0.15) + DE (0.15) → CDE (0.30).
  3. B (0.30) + CDE (0.30) → BCDE (0.60).
  4. A (0.40) + BCDE (0.60) → root.

Codewords (left = 0): A = 0, B = 10, C = 110, D = 1110, E = 1111. Lengths 1,2,3,4,41, 2, 3, 4, 4; Kraft sum 12+14+18+116+116=1\tfrac12 + \tfrac14 + \tfrac18 + \tfrac1{16} + \tfrac1{16} = 1.

Expected length:

L=0.4(1)+0.3(2)+0.15(3)+0.1(4)+0.05(4)=2.05 bits.L = 0.4(1) + 0.3(2) + 0.15(3) + 0.1(4) + 0.05(4) = 2.05 \text{ bits}.

Entropy:

H=−(0.4log⁡20.4+0.3log⁡20.3+0.15log⁡20.15+0.1log⁡20.1+0.05log⁡20.05)≈2.009 bits.H = -\left(0.4\log_2 0.4 + 0.3\log_2 0.3 + 0.15\log_2 0.15 + 0.1\log_2 0.1 + 0.05\log_2 0.05\right) \approx 2.009 \text{ bits}.

A fixed-length code needs ⌈log⁡25⌉=3\lceil \log_2 5 \rceil = 3 bits. Huffman saves 32% and sits within 0.05 bits of the entropy bound; the gap exists because ideal lengths like −log⁡20.3≈1.74-\log_2 0.3 \approx 1.74 are not integers. When every probability is a power of 12\tfrac12, Huffman hits HH exactly.

Cross-entropy and KL divergence

Suppose the true distribution is pp but you design your code (or your bets, or your model) for qq, using lengths −log⁡2q(x)-\log_2 q(x). The expected length is the cross-entropy

H(p,q)=−∑xp(x)log⁡2q(x)=H(p)+D(p ∥ q),H(p, q) = -\sum_x p(x)\log_2 q(x) = H(p) + D(p \,\|\, q),

where the Kullback–Leibler divergence

D(p ∥ q)=∑xp(x)log⁡2p(x)q(x)D(p \,\|\, q) = \sum_x p(x)\log_2\frac{p(x)}{q(x)}

is the extra bits per symbol you pay for using the wrong model.

Properties worth knowing cold:

  • Gibbs' inequality: D(p ∥ q)≥0D(p \,\|\, q) \ge 0, with equality only if p=qp = q. Proof: −D=Ep[log⁡2(q/p)]≤log⁡2Ep[q/p]≤log⁡21=0-D = E_p[\log_2(q/p)] \le \log_2 E_p[q/p] \le \log_2 1 = 0 by Jensen.
  • Not symmetric: D(p ∥ q)≠D(q ∥ p)D(p \,\|\, q) \ne D(q \,\|\, p) in general, so it is not a distance. For coins, D(Ber(0.9) ∥ Ber(0.5))≈0.531D(\text{Ber}(0.9) \,\|\, \text{Ber}(0.5)) \approx 0.531 bits but D(Ber(0.5) ∥ Ber(0.9))≈0.737D(\text{Ber}(0.5) \,\|\, \text{Ber}(0.9)) \approx 0.737 bits.
  • Infinite when qq rules out what pp allows: if q(x)=0<p(x)q(x) = 0 < p(x) the divergence is infinite. Overconfident models are punished without limit.
  • Maximum entropy, proved: with uu uniform on nn points, D(p ∥ u)=log⁡2n−H(p)≥0D(p \,\|\, u) = \log_2 n - H(p) \ge 0.

Machine-learning link. Minimising the average log loss −1N∑ilog⁡qθ(yi)-\frac1N\sum_i \log q_\theta(y_i) is minimising the cross-entropy between the empirical distribution and the model. Since H(p)H(p) does not depend on θ\theta, this is the same as minimising D(p ∥ qθ)D(p \,\|\, q_\theta), which is the same as maximum likelihood.

Worked example

the cost of the wrong code

Four symbols occur with probabilities p=(12,14,18,18)p = (\tfrac12, \tfrac14, \tfrac18, \tfrac18). An engineer assumes they are equally likely and uses a 2-bit code. How many bits per symbol does this cost, and how much is wasted?

Show solution

Optimal cost. All probabilities are powers of 12\tfrac12, so the ideal lengths 1,2,3,31, 2, 3, 3 are integers (codewords 0, 10, 110, 111) and

H(p)=12(1)+14(2)+18(3)+18(3)=1.75 bits.H(p) = \tfrac12(1) + \tfrac14(2) + \tfrac18(3) + \tfrac18(3) = 1.75 \text{ bits}.

Actual cost. With qq uniform, every symbol costs −log⁡214=2-\log_2 \tfrac14 = 2 bits, so H(p,q)=2H(p, q) = 2.

Waste. D(p ∥ q)=H(p,q)−H(p)=0.25D(p \,\|\, q) = H(p, q) - H(p) = 0.25 bits per symbol, a 14% overhead. Directly: 12log⁡22+14log⁡21+2⋅18log⁡212=0.5+0−0.25=0.25\tfrac12\log_2 2 + \tfrac14\log_2 1 + 2 \cdot \tfrac18 \log_2 \tfrac12 = 0.5 + 0 - 0.25 = 0.25.

The same distribution reappears in the betting lesson, where these 0.25 bits become a growth rate.

Knowledge check

A coin lands heads with probability 0.9. What is the entropy of one flip, to three decimals?

Knowledge check

You must identify the face of a fair six-sided die using an optimal prefix code (equivalently, an optimal yes/no questioning strategy) for one roll at a time. What is the expected number of bits?

Knowledge check

A fair coin is encoded with the ideal code for a coin with P(H)=0.9P(H) = 0.9, i.e. lengths −log⁡20.9-\log_2 0.9 for heads and −log⁡20.1-\log_2 0.1 for tails. What is the expected number of bits per flip?

Key takeaways

  • H(X)=E[−log⁡2p(X)]H(X) = E[-\log_2 p(X)]: expected surprise, and the minimum average number of yes/no questions to identify XX.
  • The uniform distribution maximises entropy on a finite set (log⁡2n\log_2 n); the normal maximises it for a given variance.
  • Chain rule: H(X,Y)=H(X)+H(Y∣X)H(X, Y) = H(X) + H(Y \mid X); conditioning never increases entropy on average.
  • Prefix codes satisfy Kraft, have L≥HL \ge H, and Huffman achieves H≤L<H+1H \le L < H + 1.
  • Cross-entropy H(p,q)=H(p)+D(p ∥ q)H(p, q) = H(p) + D(p \,\|\, q); KL divergence is the non-negative, asymmetric cost of using the wrong model, and minimising log loss minimises it.

Finished reading?

Answer the 3 knowledge checks to complete this lesson (0 done).