AI-210 · Lesson 9 of 12 · 30 min
Information theory: entropy and divergence
In 1948 Claude Shannon, an engineer at Bell Labs, published "A Mathematical Theory of Communication", which defined how to measure information and set the limits on how far data can be compressed and how fast it can be sent over a noisy channel. Shannon's ideas underpin every modem, every compressed file and every fiber link in a data center. They also turned out to be central to machine learning. The loss used to train almost every classifier and every large language model is a quantity from information theory, the cross-entropy; the way models are compared with each other and with data uses the Kullback–Leibler divergence; and the quality of a language model is reported as perplexity, an information-theoretic measure.
This chapter defines information content, entropy, cross-entropy, KL divergence and mutual information, shows how they relate, and connects each to its use in machine learning.
Information content
How much information does learning an outcome give you? Shannon's answer: the less probable the outcome, the more informative it is. The information content (or surprisal) of an outcome with probability \(p\) is
A fair coin flip gives \(-\log_2 0.5 = 1\) bit. Learning which of 8 equally likely outcomes occurred gives 3 bits, because it answers three yes/no questions. An event with probability 1 gives 0 bits: you learn nothing from being told what you already knew. Information from independent events adds, because their probabilities multiply and the logarithm turns products into sums. Using the natural logarithm instead of base 2 measures information in nats (1 nat = 1.443 bits); machine learning code usually works in nats.
Entropy
The entropy of a distribution is its expected information content: how surprised you are, on average, by an outcome drawn from it:
Entropy measures uncertainty. It is zero when one outcome is certain and largest when all outcomes are equally likely: for \(K\) outcomes, the maximum is \(\log_2 K\) bits. Shannon's source coding theorem gives it a concrete meaning: the entropy is the minimum average number of bits per symbol needed to encode messages from the distribution without loss. No compressor can do better.
import numpy as np
def entropy(p):
p = np.asarray(p, dtype=float)
p = p[p > 0] # 0 log 0 is taken as 0
return -np.sum(p * np.log2(p)) + 0.0 # + 0.0 turns -0.0 into 0.0
for name, p in [("fair coin", [0.5, 0.5]), ("biased coin", [0.9, 0.1]),
("fair die", [1/6] * 6), ("certain", [1.0, 0.0])]:
print(f"{name:12s} H = {entropy(p):.3f} bits")fair coin H = 1.000 bits biased coin H = 0.469 bits fair die H = 2.585 bits certain H = 0.000 bits
Worked problem
Entropy and compression
A sensor reports one of four states with probabilities 0.5, 0.25, 0.125 and 0.125. Find the entropy, and compare it with a fixed 2-bit code.
Show solution
- \(H = 0.5 \times 1 + 0.25 \times 2 + 0.125 \times 3 + 0.125 \times 3 = 0.5 + 0.5 + 0.375 + 0.375 = 1.75\) bits.
- A variable-length code matching \(-\log_2 p\) uses codewords of 1, 2, 3 and 3 bits (for example 0, 10, 110, 111), averaging exactly 1.75 bits.
- A fixed-length code needs 2 bits for four states.
Answer: 1.75 bits per reading, a 12.5% saving over the 2-bit fixed code. Giving short codes to common symbols and long codes to rare ones is the idea behind Huffman coding and every modern compressor.
Cross-entropy
Suppose the data really come from a distribution \(p\), but we encode or predict them using a model \(q\). The average number of bits needed is the cross-entropy:
It is always at least \(H(p)\), with equality only when \(q = p\): using the wrong distribution costs extra bits. This is exactly the classification loss from Lessons 4 and 6. For a single training example whose true class is \(c\), the target distribution \(p\) is one-hot (1 for class \(c\), 0 elsewhere), and the cross-entropy reduces to \(-\log q(c)\), the negative log-probability the model assigns to the right answer. Averaging over a training set, minimizing cross-entropy is the same as maximizing likelihood.
Worked problem
Cross-entropy loss for one example
A three-class classifier outputs \(q = (0.7, 0.2, 0.1)\). Find the loss in nats if the true class is 1, and if it is 3.
Show solution
- True class 1: \(-\ln 0.7 = 0.357\) nats.
- True class 3: \(-\ln 0.1 = 2.303\) nats.
Answer: 0.357 nats when the model is right and confident, 2.303 nats when it gave the true class only 10%. The loss grows without limit as the probability of the true class approaches zero, which strongly penalizes confident mistakes.
Kullback–Leibler divergence
The extra cost of using \(q\) instead of \(p\) is the Kullback–Leibler (KL) divergence:
KL divergence is never negative, and it is zero only when the two distributions are identical (Gibbs' inequality). It is a natural measure of how different a model is from the truth. Since \(H(p)\) does not depend on the model, minimizing cross-entropy over \(q\) is the same as minimizing \(D_{\text{KL}}(p\,\|\,q)\).
KL divergence is not a distance in the geometric sense: it is not symmetric, \(D_{\text{KL}}(p\|q) \ne D_{\text{KL}}(q\|p)\) in general, and it does not satisfy the triangle inequality. The asymmetry matters. \(D_{\text{KL}}(p\|q)\) is large wherever \(p\) has probability and \(q\) has very little, so minimizing it forces \(q\) to cover everything \(p\) can do ("mass-covering"). \(D_{\text{KL}}(q\|p)\) penalizes \(q\) for putting probability where \(p\) has little, so minimizing it makes \(q\) concentrate on a high-probability region of \(p\) ("mode-seeking"). Variational inference (AI-320) uses the second form.
import numpy as np
p = np.array([0.6, 0.3, 0.1]) # true distribution
q = np.array([0.4, 0.4, 0.2]) # model distribution
H_p = -np.sum(p * np.log2(p))
H_pq = -np.sum(p * np.log2(q)) # cross-entropy
KL_pq = np.sum(p * np.log2(p / q))
KL_qp = np.sum(q * np.log2(q / p))
print(f"H(p) = {H_p:.4f} H(p, q) = {H_pq:.4f} bits")
print(f"KL(p||q) = {KL_pq:.4f} = H(p,q) - H(p) = {H_pq - H_p:.4f}")
print(f"KL(q||p) = {KL_qp:.4f} (not symmetric)")H(p) = 1.2955 H(p, q) = 1.4219 bits KL(p||q) = 0.1265 = H(p,q) - H(p) = 0.1265 KL(q||p) = 0.1320 (not symmetric)
KL divergence appears throughout modern AI: as a regularizer that keeps a fine-tuned language model close to its original (in reinforcement learning from human feedback, a KL penalty stops the model drifting too far), in knowledge distillation (training a small model to match the output distribution of a large one), in variational autoencoders, and in measuring how much a data distribution has shifted between training and deployment.
Perplexity
A language model assigns a probability to each next token. Its cross-entropy on a test text is the average negative log-probability of the tokens that actually occurred. Perplexity is the exponential of that cross-entropy:
It has an intuitive meaning: a perplexity of 20 means the model is, on average, as uncertain as if it were choosing uniformly among 20 tokens. Lower is better. A model guessing uniformly over a vocabulary of 50,000 tokens has a perplexity of 50,000; strong language models reach single-digit perplexities on ordinary text.
import numpy as np
# Probabilities a language model assigned to each actual next token in a short text
probs = np.array([0.40, 0.05, 0.62, 0.21, 0.09, 0.33, 0.71, 0.12])
nll = -np.mean(np.log(probs)) # average cross-entropy in nats per token
print(f"cross-entropy {nll:.3f} nats/token = {nll / np.log(2):.3f} bits/token")
print(f"perplexity {np.exp(nll):.2f}")
print("perplexity of guessing uniformly among 50,000 tokens:", 50_000)cross-entropy 1.491 nats/token = 2.151 bits/token perplexity 4.44 perplexity of guessing uniformly among 50,000 tokens: 50000
Perplexity and cross-entropy also connect language modeling to compression: a model with a cross-entropy of 2.15 bits per token could, in principle, compress the text to about 2.15 bits per token using arithmetic coding. Predicting well and compressing well are the same problem.
Mutual information
How much does knowing one variable tell you about another? The mutual information between \(X\) and \(Y\) is the reduction in uncertainty about one from learning the other:
It is zero if and only if \(X\) and \(Y\) are independent, and unlike correlation it captures any kind of dependence, not just linear relationships. It is used to select informative features, to build decision trees (where it is called information gain: each split is chosen to reduce the entropy of the labels as much as possible), and in representation learning.
import numpy as np
# Joint distribution of X = "inlet temperature high?" and Y = "fan alarm?"
P = np.array([[0.60, 0.05], # X = low: Y = no, yes
[0.10, 0.25]]) # X = high: Y = no, yes
px, py = P.sum(axis=1), P.sum(axis=0)
H = lambda d: -np.sum(d[d > 0] * np.log2(d[d > 0]))
MI = np.sum(P * np.log2(P / np.outer(px, py)))
print(f"H(X) = {H(px):.3f}, H(Y) = {H(py):.3f}, H(X,Y) = {H(P.ravel()):.3f} bits")
print(f"I(X;Y) = {MI:.3f} bits = H(X) + H(Y) - H(X,Y) = {H(px) + H(py) - H(P.ravel()):.3f}")H(X) = 0.934, H(Y) = 0.881, H(X,Y) = 1.490 bits I(X;Y) = 0.325 bits = H(X) + H(Y) - H(X,Y) = 0.325
Worked problem
Information gain for a decision tree split
A set of 8 servers has 4 that failed and 4 that did not (entropy 1 bit). Splitting on "fan alarm" gives one group of 4 servers (3 failed, 1 not) and another of 4 (1 failed, 3 not). What is the information gain?
Show solution
- Entropy of each group: \(H(0.75, 0.25) = -(0.75\log_2 0.75 + 0.25\log_2 0.25) = 0.811\) bits.
- Weighted entropy after the split: \(0.5 \times 0.811 + 0.5 \times 0.811 = 0.811\) bits.
- Information gain: \(1 - 0.811 = 0.189\) bits.
Answer: 0.189 bits. A decision tree compares this gain with the gains of other possible splits and chooses the largest.
Label smoothing and calibration
Because cross-entropy rewards pushing the probability of the correct class all the way to 1, models trained with it can become overconfident. Label smoothing replaces the one-hot target with a slightly softened one (for example 0.9 for the correct class and the remaining 0.1 shared among the others), which raises the entropy of the target and discourages extreme confidence. A model is well calibrated when its stated probabilities match observed frequencies: among predictions made with 80% confidence, about 80% should be right. Calibration matters whenever probabilities feed decisions, such as deciding whether to alert an operator or to defer to a human.
Common mistakes
MistakeMixing bits and nats.
Insteadlog₂ gives bits, ln gives nats; 1 nat = 1.443 bits. Frameworks report losses in nats.
MistakeTreating KL divergence as a symmetric distance.
InsteadD_KL(p‖q) ≠ D_KL(q‖p); the direction changes what is penalized.
MistakeComputing log(0) when a model assigns zero probability.
InsteadClip probabilities or work with logits and log-softmax for numerical stability.
MistakeComparing perplexities of models with different tokenizers.
InsteadPerplexity is per token; different vocabularies split text differently, so compare bits per character or per word instead.
MistakeAssuming zero correlation means no dependence.
InsteadMutual information detects any dependence; correlation only detects linear relationships.
Summary and key terms
- Information content \(-\log_2 p\): rare outcomes carry more bits; independent information adds.
- Entropy \(H(p) = -\sum p\log p\) measures uncertainty and is the limit of lossless compression; maximum \(\log_2 K\) for \(K\) outcomes.
- Cross-entropy \(H(p, q)\) is the cost of predicting \(p\) with \(q\); with one-hot targets it is the classification loss \(-\log q(\text{true class})\).
- KL divergence \(D_{\text{KL}}(p\|q) = H(p, q) - H(p) \ge 0\), zero only when \(p = q\), and not symmetric.
- Minimizing cross-entropy = minimizing KL to the data = maximizing likelihood.
- Perplexity = exp(cross-entropy per token): the effective number of choices a language model is unsure between.
- Mutual information \(I(X;Y) = H(X) + H(Y) - H(X, Y)\) measures any dependence; it is the information gain used by decision trees.
- KL terms regularize fine-tuning and distillation; label smoothing and calibration address overconfidence.
- Information content
- The surprisal of an outcome, \(-\log p\), in bits or nats.
- Bit
- The unit of information from a base-2 logarithm: one fair yes/no answer.
- Nat
- The unit of information from a natural logarithm; 1 nat = 1.443 bits.
- Entropy
- The expected information content of a distribution, measuring its uncertainty.
- Source coding theorem
- Shannon's result that entropy is the minimum average code length for lossless compression.
- Cross-entropy
- The average information needed to encode data from \(p\) using a code optimized for \(q\).
- KL divergence
- The extra information cost of using \(q\) instead of \(p\); a non-negative, asymmetric measure of difference.
- Perplexity
- The exponential of the per-token cross-entropy of a language model.
- Joint entropy
- The entropy of two variables taken together.
- Conditional entropy
- The remaining uncertainty in one variable after another is known.
- Mutual information
- The reduction in uncertainty about one variable from knowing another.
- Information gain
- The reduction in label entropy from a split in a decision tree.
- Label smoothing
- Softening one-hot training targets to discourage overconfidence.
- Calibration
- Agreement between a model's stated probabilities and observed frequencies.
Practice problems
Work each problem on paper first, then reveal the answer to check.
How many bits of information does learning the outcome of a fair 16-sided die give?
Show answer
log₂ 16 = 4 bits.
Find the entropy of the distribution (0.5, 0.5, 0, 0) and of (0.25, 0.25, 0.25, 0.25).
Show answer
1 bit and 2 bits.
What is the entropy of a coin with P(heads) = 0.8?
Show answer
−(0.8 log₂ 0.8 + 0.2 log₂ 0.2) = 0.258 + 0.464 = 0.722 bits.
A model assigns probability 0.05 to the correct class. What is the cross-entropy loss in nats and in bits?
Show answer
−ln 0.05 = 3.00 nats = 4.32 bits.
For p = (0.5, 0.5) and q = (0.9, 0.1), compute D_KL(p‖q) in bits.
Show answer
0.5 log₂(0.5/0.9) + 0.5 log₂(0.5/0.1) = 0.5(−0.848) + 0.5(2.322) = 0.737 bits.
Compute D_KL(q‖p) for the same distributions and compare.
Show answer
0.9 log₂(0.9/0.5) + 0.1 log₂(0.1/0.5) = 0.763 − 0.232 = 0.531 bits; different from 0.737, showing the asymmetry.
A language model has a cross-entropy of 2.3 nats per token. What is its perplexity?
Show answer
e^2.3 = 9.97, about 10.
If a model's perplexity falls from 20 to 10, how much has its cross-entropy fallen, in bits per token?
Show answer
log₂ 20 − log₂ 10 = 1 bit per token.
X and Y are independent. What is I(X; Y), and what is H(X, Y) in terms of H(X) and H(Y)?
Show answer
I = 0 and H(X, Y) = H(X) + H(Y).
A split divides 10 examples (5 positive, 5 negative) into a pure group of 5 positives and a pure group of 5 negatives. What is the information gain?
Show answer
Before: 1 bit. After: both groups have entropy 0. Gain = 1 bit, the maximum possible.
Lesson quiz · 5 questions
Score 60% or more to complete this lesson.
Create a free account to save your progress, take quizzes and earn a certificate.