Mathematical foundations
Entropy, Cross-Entropy, KL Divergence, and Mutual Information
Understand coding-based interpretations of entropy, cross-entropy, KL divergence, mutual information, and their use in ML objectives.
By the end you can
- Compute and interpret entropy, cross-entropy, and KL divergence for discrete distributions
- Explain why cross-entropy differs from entropy by a KL term
- Interpret mutual information as reduction in uncertainty or divergence from independence
- Recognize asymmetry, support, estimation, and semantic limitations of information measures
Comparison
KL divergence is not a distance metric
KL divergence is asymmetric. It generally violates the triangle inequality. Its name encourages geometric intuitions that do not hold, and the useful question is not whether it is a metric — it is not — but which repair of it does buy one. That question has a published answer.
There is one, and it is short. Take the Jensen–Shannon divergence and take its square root. The result is symmetric, bounded, and satisfies the triangle inequality. Endres and Schindelin published it in IEEE Transactions on Information Theory in July 2003, and their abstract states the result plainly: “We introduce a metric for probability distributions, which is bounded, information-theoretically motivated, and has a natural Bayesian interpretation”. Österreicher and Vajda established the same class of metric divergences independently that year, in the Annals of the Institute of Statistical Mathematics. The Jensen–Shannon divergence is the β = 1 member of that class.
One paper puts the two square roots side by side in a single paragraph. Kazuki Okamura, writing in 2023 on metrizing powers of the Jensen–Shannon divergence, notes that “It is well-known that the square root of the JSD satisfies the triangle inequality ([11, 12, 13]),” citing Endres and Schindelin among others. The same paragraph continues: “However, the square root of the KLD is generally not a metric: it can be asymmetric and violate the triangle inequality.” Taking a square root repairs Jensen–Shannon. It does not repair KL.
So the three columns. Forward KL p‖q is the expected log ratio under p: nonnegative, zero only when the distributions agree almost everywhere, asymmetric, and infinite under support mismatch. Reverse KL q‖p weights the regions where q places mass, can settle on one mode of a multimodal target, and optimizes differently. The third column is a genuine metric — which KL is not, and √JSD is.
KL p||q
Expected log ratio under p.
- Nonnegative under standard conditions
- Zero only when distributions agree almost everywhere
- Asymmetric
- Can be infinite under support mismatch
Reverse KL q||p
Expected log ratio under q.
- Emphasizes regions where q places mass
- Can prefer one mode in multimodal targets
- Different optimization behavior from forward KL
- Not interchangeable with p||q
Metric distance
Satisfies symmetry and triangle inequality.
- KL lacks both properties
- Supports ordinary geometric neighborhoods
- May be built from other divergences
- Requires interpretation appropriate to the space
Information theory begins with a coding problem
A source selects messages according to a probability distribution. Give the common messages short codes and the rare ones longer codes, and the average code length falls. Entropy quantifies the irreducible average uncertainty of that source under ideal coding assumptions. Cross-entropy measures the coding cost when data from one distribution are encoded using probabilities from another.
That is not only a definition. It has been measured, on a source every reader of this lesson already uses. English.
Start with a 26-letter alphabet used with no statistical structure at all: log2 26 = 4.7 bits per letter. Statistics spanning eight letters bring the figure down to roughly 2.3 bits per letter. Then give a guesser the hundred letters that came before. Shannon's 1951 prediction experiments did exactly that, and in the §6 table, "Experimental Bounds for English," the column for 100 known preceding letters reads Upper 1.3, Lower .6. He states the conclusion in his introduction: “From this analysis it appears that, in ordinary literary English, the long range statistical effects (up to 100 letters) reduce the entropy to something of the order of one bit per letter, with a corresponding redundancy of roughly 75%.”
The estimate was later checked by a different instrument. In 1978 Cover and King ran a sequential-betting experiment at 27-for-1 odds and got about 1.3 bits per symbol, which they said agreed with Shannon's estimate. Guerrero's 2009 review of the classical figures summarises the pair: “Cover and King, using gambling estimates, found a value between 1.25 and 1.35 bits per character”.
Read what that collapse from 4.7 to roughly one bit is, and what it is not. It is a statement about redundancy in the letter stream — about how much of each letter is already implied by the hundred before it. These measures concern distributions over possibilities. They do not measure truth, usefulness, causal importance, or human meaning.
Information measures quantify uncertainty and distributional mismatch, not semantic value.
Case
Shannon, 1948: meaning declared irrelevant to the engineering problem
Shannon set these terms in 1948, in the Bell System Technical Journal. The paper says early on that the “semantic aspects of communication are irrelevant to the engineering problem”. The exclusion is deliberate, and it is load-bearing. Everything measured in this lesson — the 4.7 bits per letter, the 1.3, the nats — is measured after that sentence has thrown meaning out of scope.
Analogy
Short envelopes for frequent messages, long ones for rare
Frequently requested messages are stored in small envelopes and rare messages in larger ones. A coding plan based on the correct frequencies minimizes average material. Using the wrong frequency table wastes space. KL divergence measures the expected extra material caused by that mismatch. A rare emergency message may matter far more than its coding length suggests, and no envelope size records that.
The divergence has a birth date. Kullback and Leibler introduced it in 1951, in the Annals of Mathematical Statistics.
Information-theoretic efficiency is about probability-weighted coding, not the human value of a message.
Visual
How the core quantities fit together
With a true distribution p and model q, cross-entropy decomposes into entropy plus KL divergence: H(p,q) = H(p) + DKL(p‖q). The KL term cannot be negative. So a measured cross-entropy is an upper bound on the entropy of the source. That is what makes the decomposition an experimental instrument rather than an identity to memorise, and it is how the entropy of English has actually been bounded from above.
The experiment has been run. Brown and four colleagues built a word trigram model on 583 million words and scored it against a balanced sample: the 5.96-million-character Brown Corpus, over an alphabet of 95 printable ASCII characters. Their 1992 abstract gives the design and the result in one sentence: “We present an estimate of an upper bound of 1.75 bits for the entropy of characters in printed English, obtained by constructing a word trigram model and then computing the cross-entropy between this model and a balanced sample of English text.” The inequality that licenses the whole thing is H(P) ≤ H(P,M).
Because the bound is a property of the model, a better model lowers it. In 2018 Takahashi and Tanaka-Ishii restated the earlier figure — “They reported an estimated upper bound of 1.75 bpc for English” — and reported their own, from neural language models: “We finally obtain an estimated entropy rate value of 1.12 bpc for English characters”. Neither number is the entropy of English. Both are ceilings. The drop from 1.75 to 1.12 bits per character is a shrinking mismatch term, not a change in the language.
The four quantities in play, then. Entropy H(p) is the average surprise when outcomes follow p and coding matches p. Cross-entropy H(p,q) is the average negative log probability that q assigns to outcomes from p. KL divergence DKL(p‖q) is the extra expected coding cost of using q instead of p. And mutual information I(X;Y) is the KL divergence between the joint p(x,y) and the independent product p(x)p(y).
- 1
Entropy H(p)
Average surprise when outcomes follow p and coding matches p.
- 2
Cross-entropy H(p,q)
Average negative log probability assigned by q to outcomes from p.
- 3
KL divergence DKL(p||q)
Extra expected coding cost from using q instead of p.
- 4
Mutual information I(X;Y)
KL divergence between the joint p(x,y) and independent product p(x)p(y).
Cross-entropy = entropy of the source + mismatch cost, which is why a measured 1.75 bpc is a ceiling and not an answer.
Example
A binary prediction under confident error
Suppose the true label is 1 and a model predicts q=0.9 or q=0.01. Both are wrong-or-right by the same accuracy count. The losses are not remotely the same. That asymmetry is why log loss is the training objective — and also why a falling training loss is not evidence that the reported probabilities are honest. Guo and three colleagues measured that gap directly on CIFAR-100, using expected calibration error at M = 15 bins before and after each correction.
- High confidence correct: Loss −log(0.9) is small.
- High confidence wrong: Loss −log(0.01) is much larger.
- Reason: Log loss strongly penalizes assigning little probability to the event that occurred.
- Calibration link: Expected log loss rewards truthful probabilities under the assumed evaluation distribution. Rewarding them is not the same as producing them. Guo, Pleiss, Sun and Weinberger open their 2017 paper on calibration with the finding: “While neural networks today are undoubtedly more accurate than they were a decade ago, we discover with great surprise that modern neural networks are no longer well-calibrated.”
- Caution: In their Figure 1, a 5-layer LeNet on CIFAR-100 with 44.9% error had average confidence closely matching its accuracy. A 110-layer ResNet with 30.6% error — the more accurate model — was substantially overconfident, trained on exactly this loss. The published fix, temperature scaling, is a single scalar T fitted on validation negative log-likelihood; it leaves the argmax and therefore the accuracy unchanged, and was the most effective correction. Minderer and colleagues re-ran the question on newer architectures in 2021: “Many instances of miscalibration in modern neural networks have been reported... we find that the most recent models, notably those not using convolutions, are among the best calibrated”. Label noise and distribution shift can still make extreme confidence operationally costly even when training loss decreases.
Key idea
Mutual information is easy to define and hard to estimate
Mutual information is zero exactly under independence, given the usual regularity conditions. It captures nonlinear dependence, because it compares the full joint distribution with the product of marginals. In high dimensions, estimating those distributions or density ratios is difficult.
How difficult has a number on it. There is a formal ceiling on what a finite sample can support, proved by McAllester and Stratos in 2020: “More specifically, we show that any distribution-free high-confidence lower bound on mutual information estimated from N samples cannot be larger than O(ln N).” The limit is on what may honestly be reported, not on what the data contain. Ten thousand samples do not certify more than about ln N nats, however many nats the library prints.
The same wall has an operational form. Song and Ermon reported in 2020 that “estimators such as MINE exhibit variance that could grow exponentially with the true amount of underlying MI,” and that to hold the variance of the MINE and NWJ estimators constant as MI grows “one would need a batch size of n = Θ(e^{D_KL(P‖Q)})”. The contrastive alternative escapes the variance but not the ceiling: its values are “bounded by log n”. Every route out of the problem is paid for in the same currency.
Treat an estimated mutual-information value as an estimator with diagnostics, not as a ground-truth property revealed by a library call.
A high-confidence lower bound read off N samples cannot exceed O(ln N), however large the number your library prints.
Key idea
Bits, nats, and the base of the logarithm
Base-two logarithms measure information in bits. Natural logarithms measure it in nats. Changing the base multiplies every information quantity by a constant. The ordering of models under the same score is unchanged, but the magnitudes and the units are not. Reports should state the logarithm convention when values are compared across tools.
This lesson is itself a demonstration of the hazard. Shannon's bounds for English are quoted in bits per letter — 4.7, 1.3, .6. Brown and colleagues, and Takahashi and Tanaka-Ishii, report bits per character, at 1.75 and 1.12. The mutual-information results are in nats: O(ln N), 5 nats, 2 nats. Three conventions, one subject. Compare any two of those numbers without converting first and you are comparing units, not models.
Units do not turn entropy into semantic meaning or causal importance.
The logarithm base changes the unit, not the underlying uncertainty ordering.
Steps
Using an information measure responsibly
Identify the distributions and the operational claim before computing a scalar. Define p and q, stating which distribution generates the data and which is being evaluated. Check support: find events allowed by p but assigned zero or tiny probability by q. Choose direction, and say why forward or reverse KL matches the intended approximation. Validate the estimation. Then limit the claim — do not equate information with causality, fairness, usefulness, or semantic meaning.
Step four is the one usually skipped, and it is the one with a published protocol. The trouble starts with the estimators themselves. Gao, Ver Steeg and Galstyan open their 2015 paper with the diagnosis: “We demonstrate that a popular class of non-parametric mutual information (MI) estimators based on k-nearest-neighbor graphs requires number of samples that scales exponentially with the true MI.”
A 2023 benchmark built the test bench for that claim: nine estimators, forty tasks with known ground-truth MI, N = 10,000 points per run. Its authors restate the earlier finding — “Gao et al. (2015) proves that estimation of MI between strongly interacting variables requires large sample sizes” — and then measure where the estimators break: “for Gaussian distributions, neural estimators (and the simple CCA baseline) are accurate even up to 5 nats, while after the application of the spiral diffeomorphism, the estimates become inaccurate already at 2 nats”. The diffeomorphism is a smooth change of coordinates that provably leaves the true mutual information unchanged. Nothing about the dependence moved. Only the axes did, and the accurate range fell from about 5 nats to 2.
So validating an estimator means running it on distributions whose MI you already know, in coordinates as awkward as the ones you will deploy in, and reporting the value at which it stops working. Two nats is a finding. "We used a library" is not.
1. Define p and q
State which distribution generates data and which distribution is being evaluated.
2. Check support
Find events allowed by p but assigned zero or tiny probability by q.
3. Choose direction
Explain why forward or reverse KL matches the intended approximation.
4. Validate estimation
Use known cases, resampling, and dimensionality-aware diagnostics.
5. Limit the claim
Do not equate information with causality, fairness, usefulness, or semantic meaning.
Why information uses logarithms
Self-information assigns −log p(x) to an outcome. Rare outcomes are more surprising, and the surprises of independent events add, because logarithms turn products into sums. The log base determines the units: base two gives bits, the natural logarithm gives nats. log2 26 = 4.7 bits is the per-letter cost of a 26-letter alphabet carrying no statistical structure, and every regularity in the source pushes that number down. A zero model probability for an event that occurs under p creates infinite cross-entropy and KL divergence, because no finite code was allocated.
Key takeaways
- Entropy quantifies probability-weighted uncertainty and ideal average coding cost: Shannon measured printed English at 4.7 bits per letter with no statistical structure and at an upper 1.3, lower .6 bits per letter once 100 preceding letters are known.
- Cross-entropy evaluates how a model distribution scores data from another distribution — which is how Brown and four colleagues published 1.75 bits per character as an upper bound on the entropy of English in 1992, and how Takahashi and Tanaka-Ishii later lowered it to 1.12.
- KL divergence is the nonnegative mismatch term between cross-entropy and source entropy, so a measured cross-entropy is always a ceiling and a better model lowers it.
- KL direction matters because the divergence is asymmetric and reacts differently to missing support and extra modes; the square root of the Jensen–Shannon divergence is a bounded metric (Endres and Schindelin, 2003), and the square root of KL is not.
- Mutual information measures dependence as divergence between a joint distribution and the product of its marginals, but McAllester and Stratos showed no distribution-free high-confidence lower bound from N samples can exceed O(ln N), and a benchmark at N = 10,000 saw estimates fail at 2 nats after a coordinate change that left the true MI untouched.
- Information-theoretic quantities do not automatically measure causality, semantic value, or operational usefulness: Shannon ruled the semantic aspects out of the engineering problem in 1948, and cross-entropy training alone left a 110-layer ResNet at 30.6% error more overconfident than a LeNet at 44.9%.