Classical Information Theory
Classical Information Theory
Shannon asked a question with a number for an answer: how many bits does it take to describe the output of a random source? The answer — entropy — and its relatives (mutual information, relative entropy) are the classical skeleton on which the quantum theory of von Neumann entropy and quantum mutual information is built.
Learning Objectives
By the end of this lesson you will be able to:
- Define Shannon entropy , joint entropy , and conditional entropy , and state their units.
- Define mutual information and relative entropy (KL divergence) , and relate them.
- Prove non-negativity of KL divergence via Gibbs' inequality, and derive as a corollary.
- Apply the chain rule for entropy and state the data-processing inequality.
- Explain the source-coding theorem's operational meaning (entropy as the compression limit).
- Compute entropy, mutual information, and KL divergence for sample distributions in NumPy.
Intuition
Information is surprise. An outcome you were sure of carries no information; a rare outcome carries a lot. Shannon's masterstroke was to insist the measure of surprise be additive for independent events — learning two independent facts should cost the sum of their individual costs. The only function (up to a constant fixing the unit) that turns multiplication of probabilities into addition is the logarithm, so the surprise of an outcome with probability is . Entropy is the average surprise of a source.
From this one idea everything follows:
- Entropy — your average uncertainty about before seeing it; equivalently, the minimum bits/symbol to compress a stream of i.i.d. 's.
- Conditional entropy — uncertainty about that remains after you learn .
- Mutual information — uncertainty about that learning removes; the shared information between two variables.
- Relative entropy — the penalty (in extra bits) you pay for compressing data that's really distributed as using a code optimized for the wrong distribution .
These are not just analogies; each has an operational coding theorem behind it. And each has a direct quantum descendant — the von Neumann entropy replaces , and quantum mutual information replaces — which we develop once density matrices arrive in Term 1.5.
Theory
Throughout, so information is measured in bits; using gives nats (natural units), differing only by the constant factor . We adopt the standard convention , justified by .
Shannon entropy
For a discrete random variable with PMF over alphabet , the Shannon entropy is the expected surprise:
Properties. (each term on ), with iff is deterministic. And , with equality iff is uniform — we prove this below as a one-line corollary of Gibbs' inequality. For a binary variable with , the binary entropy function is
peaking at bit (a fair coin / equal superposition is maximally uncertain) and vanishing at .
Joint and conditional entropy
For a pair with joint PMF , the joint entropy is
and the conditional entropy of given is the expected entropy of once is known:
Chain rule. Using and :
In words: the total uncertainty in is the uncertainty in plus the leftover uncertainty in once is known. By symmetry as well. The general chain rule iterates this:
Relative entropy (KL divergence) and Gibbs' inequality
The relative entropy (Kullback–Leibler divergence) from to , two PMFs on the same alphabet, is
with the conventions and if for some with . It is not a metric — it is asymmetric, in general, and violates the triangle inequality — but it is the right notion of "statistical distance" for coding and inference: it measures the inefficiency (extra bits per symbol) of assuming the distribution is when it is really .
Theorem (Gibbs' inequality / non-negativity of KL). For any PMFs ,
Proof. Work in nats (multiply by at the end; sign unaffected). Use the fundamental bound for all , with equality iff (the line is tangent to the concave at ). Then, restricting the sum to the support ,
since . Hence . Equality requires equality in at every , forcing there, and (no -mass outside the support of ); together these give .
Corollary (uniform maximizes entropy). Let be uniform. Then
so , with equality iff . Maximum uncertainty is the uniform distribution — exactly the equal-superposition state in the quantum case.
Mutual information
The mutual information between and is the KL divergence between their joint distribution and the product of marginals:
It measures how far is from being independent. Expanding the log gives the entropy identities, all equivalent definitions:
The first form is the headline: mutual information is the reduction in uncertainty about from learning . Because is a KL divergence, Gibbs' inequality immediately gives
A useful consequence is "conditioning reduces entropy": from we get — on average, side information never hurts. (It can increase entropy for a specific value , but not on average.)
Data-processing inequality (statement)
If forms a Markov chain (i.e. depends on only through , so ), then
Post-processing cannot create information. No deterministic or randomized transformation of can increase what it tells you about — you can only lose or preserve information by processing. This single inequality underlies converse bounds in coding, the impossibility of "boosting" a noisy channel by local post-processing, and (in its quantum form) the monotonicity of quantum relative entropy under channels — a cornerstone of quantum Shannon theory [Wil].
Source coding (Shannon's first theorem) — intuition
Entropy is not merely a formula; it is an operational limit. The source-coding theorem [CT, §5] (Shannon, 1948) says: a source emitting i.i.d. symbols can be compressed losslessly to an average of bits per symbol, and no lossless scheme can do better in the limit of long blocks.
The intuition is the asymptotic equipartition property (AEP): for large , the probability of a typical length- sequence concentrates around , so there are effectively only "typical" sequences worth encoding (out of possible). Indexing just those costs bits, i.e. bits per symbol. A biased coin with bits compresses to under half a bit per flip; a fair coin () cannot be compressed at all. Entropy is the incompressible core of a source — and its quantum analog, via Schumacher's theorem, replaces with the von Neumann entropy and "bits" with "qubits."
Quantum forward-reference. Everything here has a density-matrix counterpart. Shannon entropy von Neumann entropy ; the classical mutual information quantum mutual information ; and KL divergence quantum relative entropy. We build these on Term 1.5 · The Density Operator. A striking divergence: for an entangled pure state, yet , so the conditional "entropy" can be negative — impossible classically, and a signature of entanglement.
Worked Examples
Example 1 — Entropy of a biased coin and a binary symmetric channel
(a) A coin lands heads with probability . Its entropy is
So a long stream of such flips compresses to bits per flip — you cannot do better.
(b) Send a uniform bit () through a binary symmetric channel that flips it with probability , producing . By symmetry is also uniform, so . The channel's leftover noise is bits. The information that survives the channel is
This is exactly the kind of quantity whose maximization over input distributions gives the channel capacity — the maximum reliable bits per channel use.
Example 2 — KL divergence is asymmetric, and the cost of the wrong code
Let (true) and (assumed). Compute both directions.
They differ — — confirming KL is not symmetric. Operationally, $D(p\Vert q) = 0.737p$) but you compress with a code optimized for the skewed . Both are non-negative, as Gibbs' inequality guarantees, and both would be only if .
Hands-on (Python)
We compute entropy, mutual information, and KL divergence directly from distributions, with care around the convention.
import numpy as np
# --- Base-2 entropy with the 0*log0 = 0 convention handled safely. ---
def entropy(p):
"""Shannon entropy H(p) in BITS for a probability vector p."""
p = np.asarray(p, dtype=float)
assert np.isclose(p.sum(), 1.0) and (p >= -1e-12).all(), "not a valid PMF"
nz = p[p > 0] # drop zeros: 0*log0 := 0
return float(-(nz * np.log2(nz)).sum())
def binary_entropy(p):
return entropy([p, 1 - p]) if 0 < p < 1 else 0.0
print(f"H(fair coin) = {binary_entropy(0.5):.4f} bits") # 1.0000
print(f"H(p=0.25 coin) = {binary_entropy(0.25):.4f} bits") # 0.8113
print(f"H(uniform over 4) = {entropy([0.25]*4):.4f} bits") # 2.0000 (= log2 4)# --- KL divergence D(p || q) in bits. Asymmetric by design. ---
def kl_divergence(p, q):
p = np.asarray(p, dtype=float)
q = np.asarray(q, dtype=float)
mask = p > 0 # terms with p=0 contribute 0
if np.any((q[mask] == 0)): # p>0 but q=0 -> divergence is infinite
return np.inf
return float((p[mask] * np.log2(p[mask] / q[mask])).sum())
p = np.array([0.5, 0.5])
q = np.array([0.9, 0.1])
print(f"\nD(p||q) = {kl_divergence(p, q):.4f} bits") # 0.7370
print(f"D(q||p) = {kl_divergence(q, p):.4f} bits") # 0.5310 -> asymmetric!
print(f"D(p||p) = {kl_divergence(p, p):.4f} bits") # 0.0 -> Gibbs equality
assert kl_divergence(p, q) >= 0 and kl_divergence(q, p) >= 0 # Gibbs: D >= 0# --- Joint, conditional, mutual information from a JOINT distribution P[x, y]. ---
def mutual_information(Pxy):
"""I(X;Y) in bits from a joint PMF matrix Pxy (rows=x, cols=y)."""
Pxy = np.asarray(Pxy, dtype=float)
assert np.isclose(Pxy.sum(), 1.0), "joint PMF must sum to 1"
Px = Pxy.sum(axis=1, keepdims=True) # marginal p(x)
Py = Pxy.sum(axis=0, keepdims=True) # marginal p(y)
indep = Px @ Py # product of marginals p(x)p(y)
mask = Pxy > 0
return float((Pxy[mask] * np.log2(Pxy[mask] / indep[mask])).sum())
# Binary symmetric channel, uniform input, flip prob f=0.1 (Example 1b).
f = 0.1
# joint p(x,y): P(x)=1/2 each; P(y|x) = 1-f on the diagonal, f off-diagonal.
Pxy = 0.5 * np.array([[1 - f, f],
[f, 1 - f]])
I_xy = mutual_information(Pxy)
# Cross-check against the entropy identity I = H(X) + H(Y) - H(X,Y).
Px = Pxy.sum(axis=1); Py = Pxy.sum(axis=0)
H_X = entropy(Px); H_Y = entropy(Py); H_XY = entropy(Pxy.ravel())
print(f"\nI(X;Y) direct (KL form) = {I_xy:.4f} bits")
print(f"I = H(X)+H(Y)-H(X,Y) = {H_X + H_Y - H_XY:.4f} bits")
print(f"1 - H_b(f) (theory) = {1 - binary_entropy(f):.4f} bits")
assert np.isclose(I_xy, H_X + H_Y - H_XY) # the identity holds
assert I_xy >= -1e-12 # I(X;Y) >= 0 (Gibbs)Expected output:
H(fair coin) = 1.0000 bits
H(p=0.25 coin) = 0.8113 bits
H(uniform over 4) = 2.0000 bits
D(p||q) = 0.7370 bits
D(q||p) = 0.5310 bits
D(p||p) = 0.0000 bits
I(X;Y) direct (KL form) = 0.5310 bits
I = H(X)+H(Y)-H(X,Y) = 0.5310 bits
1 - H_b(f) (theory) = 0.5310 bitsThe three independent computations of agree — a good habit: derive an information quantity
two ways and assert they match. The same entropy routine, applied to the eigenvalues of a density
matrix , will compute the von Neumann entropy in Term 1.5; classical
information theory is the literal warm-up for the quantum version.
Exercises
1. (Easy) Entropy bounds. Without computing, order these by entropy and then verify numerically: a fair 8-sided die; a fair coin; a coin with ; a deterministic source.
Solution
By and iff deterministic: deterministic < coin < fair coin < fair 8-die . The fair die maximizes entropy among these because it is uniform over the largest alphabet.
2. (Easy) Entropy is additive for independent variables. Show that if then .
Solution
Independence gives , so . Then
using and . (Equivalently: when independent, so the chain rule gives the result; and , consistent with independence.)
3. (Medium) Mutual information is symmetric. Prove directly from the entropy identities.
Solution
From the joint-entropy form, . This expression is manifestly symmetric under swapping since . Hence . Equivalently, follows from the two chain-rule expansions of . The symmetry is why we say and share bits.
4. (Medium) KL divergence between two Bernoullis. Derive a closed form for , then evaluate at and confirm it matches Example 2's .
Solution
At : $0.5\log_2\frac{0.5}{0.9} + 0.5\log_2\frac{0.5}{0.1} = 0.5(-0.848)+0.5(2.322) = 0.737D(p\Vert q)2$-symbol vectors there.)
5. (Hard) Conditioning reduces entropy — but only on average. Prove from . Then give an explicit joint distribution where for a specific value , , showing the inequality fails pointwise.
Solution
On average: (mutual information is a KL divergence, Gibbs), so .
Pointwise counterexample. Let with (so ). Let be coupled so that . Then $H(X\mid Y{=}a)=H_b(0.5)=1 > 0.469 = H(X)Y=aX$. The average is still , because other values of (e.g. making nearly certain) more than compensate. Side information helps on average, not always.
6. (Hard) Data-processing in action. Let with a uniform bit, the output of a BSC with flip , and the output of a second BSC (applied to ) with flip . Compute and and verify . (Hint: composing two BSCs gives a BSC with flip .)
Solution
For a uniform-input BSC with flip , . First channel: $I(X;Y) = 1 - H_b(0.1) = 1-0.469 = 0.531f = 0.1(0.8) + 0.9(0.2) = 0.08 + 0.18 = 0.26$, so bits. Indeed — cascading a second noisy channel destroyed information about ; post-processing into could never increase it. Numerically:
import numpy as np
def Hb(p): return 0.0 if p in (0,1) else -p*np.log2(p)-(1-p)*np.log2(1-p)
f1, f2 = 0.1, 0.2
f = f1*(1-f2) + (1-f1)*f2
print(1 - Hb(f1), 1 - Hb(f)) # 0.531..., 0.173... -> I(X;Y) >= I(X;Z)Checkpoint
- Why is the surprise of an outcome of probability defined as ? What property forces the logarithm?
- Write the chain rule for entropy and interpret each term in words.
- State Gibbs' inequality and the single calculus fact () its proof rests on.
- Give three equivalent expressions for and explain why with equality iff independence.
- State the data-processing inequality and what it forbids.
- What does the source-coding theorem say entropy operationally is, and what replaces in the quantum theory?
Answers
- We require surprise to be additive over independent events: the surprise of two independent outcomes should sum. Since their probabilities multiply, the only (continuous) function turning products into sums is the logarithm, so surprise (negative so it's positive and decreasing in ). Base 2 fixes the unit as bits.
- : total uncertainty in the pair = uncertainty in + the uncertainty in that remains once is known.
- with equality iff . Proof uses (tangent-line bound on the concave , equality at ) applied to .
- . It equals , a KL divergence, so Gibbs gives , with equality iff , i.e. .
- If is a Markov chain then : processing (deterministically or randomly) cannot increase the information it carries about .
- Entropy is the minimum average number of bits per symbol to losslessly compress an i.i.d. source — the incompressible core. In the quantum theory is replaced by the von Neumann entropy (Schumacher compression, in qubits).
Further Reading
- [CT, Ch. 2] Cover & Thomas — entropy, relative entropy, mutual information; the canonical treatment this lesson follows.
- [CT, §2.8, Ch. 5] Cover & Thomas — data-processing inequality and source coding (AEP, Shannon's first theorem).
- [Wil, Ch. 10–11] Wilde — classical entropies as the bridge to von Neumann entropy and quantum mutual information.
- [NC, §11.1–11.3] Nielsen & Chuang — Shannon entropy then von Neumann entropy; the explicit classical→quantum map.
- C. E. Shannon, "A Mathematical Theory of Communication", Bell Syst. Tech. J. 27 (1948) — the founding paper; the source-coding and channel-coding theorems originate here.
← Prev: Random Variables & Expectation · Up: Term 0 · Next: Complex Numbers & Functions →