Kullback–Leibler divergence
KL 散度
Derive the directed excess log loss, prove nonnegativity, test support and metric failures, and extend the definition carefully to probability measures.
kl-divergenceMeasure the extra log loss from using the wrong forecast
A toy signal is red with probability 3/4 and blue with probability 1/4. A reference predictor assigns each color probability 1/2. Compared with a predictor that knows the target probabilities, how much extra negative log loss does this reference incur on average?
On red, the excess is , which is positive. On blue, it is , which is negative: the reference actually predicts blue better. Averaging with the target probabilities gives about 0.130812 nats. This expected excess is the Kullback–Leibler divergence from the target to the reference.
Individual terms can be negative. The full expectation cannot, for two valid probability distributions. That distinction matters when a small evaluation sample happens to contain many blue observations: its estimated excess log loss can be negative without disproving the theorem.
The first argument decides what gets averaged
For distributions p and q on the same finite alphabet, define
We use natural logarithms, giving nats. Zero p terms contribute zero, including a coordinate where both probabilities vanish. Any coordinate with and makes the divergence infinite. On a finite alphabet, covering p’s support with positive q is sufficient for finiteness; on infinite alphabets it need not be. MIT 6.441, Section 1.2, Definition 1.4
Nonnegativity follows from concavity of log. Write S for p’s support and assume q is positive there. Jensen’s inequality gives
Equality requires both a constant ratio on S and total q mass one on S. These conditions force q=p, including zero mass outside S. If q misses part of S, the infinite case already satisfies nonnegativity. Normalizing both distributions is essential to this argument; arbitrary positive weights are not interchangeable with probabilities.
The decomposition
identifies KL as the part of cross-entropy beyond target entropy. On a finite alphabet H(p) is finite, so this statement also handles an infinite cross-entropy. Subtracting two unrelated infinities in a continuous or infinite-alphabet problem does not justify the same calculation. Deep Learning, Section 3.13, equations 3.50–3.51
KL is not a metric distance. Reversing the toy distributions gives about 0.143841 nats, not 0.130812. More sharply, whereas . The expectation changes direction along with the log ratio. It can also violate the triangle inequality: for , , and , the program below gives , larger than .
This direction affects approximation. Minimizing D(p∥q) penalizes assigning tiny q to outcomes frequent under p. Minimizing D(q∥p) instead averages where q puts its mass. Descriptions such as “covering modes” and “selecting a mode” can summarize particular restricted-family examples; they are not universal theorems about every distribution or optimizer. Deep Learning, Figure 3.6 and its qualifications
Calculate the direction you intended
This complete implementation validates finite probability vectors to absolute normalization tolerance , checks support before logarithms, and uses log differences instead of forming p/q. That avoids an intermediate ratio overflow when q is tiny. fsum reduces summation error across positive and negative terms.
import math
def probability_vector(values):
values = tuple(values)
if not values or any(not math.isfinite(v) or not 0 <= v <= 1 for v in values):
raise ValueError("nonempty finite probabilities in [0,1] required")
if not math.isclose(math.fsum(values), 1., rel_tol=0., abs_tol=1e-12):
raise ValueError("probabilities must sum to one")
return values
def kl_divergence(target, reference):
p, q = probability_vector(target), probability_vector(reference)
if len(p) != len(q):
raise ValueError("aligned category vectors required")
if any(pi > 0 and qi == 0 for pi, qi in zip(p, q)):
return math.inf
terms = [pi*(math.log(pi)-math.log(qi))
for pi, qi in zip(p, q) if pi > 0]
return math.fsum(terms)
p, q = [.75,.25], [.5,.5]
forward, reverse = kl_divergence(p,q), kl_divergence(q,p)
assert math.isclose(forward, .13081203594113697)
assert math.isclose(reverse, .14384103622589045)
assert not math.isclose(forward, reverse)
assert kl_divergence([1,0],[1,0]) == 0
assert kl_divergence([.5,.5],[1,0]) == math.inf
assert math.isclose(kl_divergence([1,0],[.5,.5]), math.log(2))
a,b,c = [.1,.9],[.2,.8],[.4,.6]
assert kl_divergence(a,c) > kl_divergence(a,b)+kl_divergence(b,c)
print("forward:",forward,"reverse:",reverse)
print("triangle:",kl_divergence(a,c),
"versus",kl_divergence(a,b)+kl_divergence(b,c))
The calculation takes O(K) scalar work and O(K) auxiliary storage for K categories. The mathematical result is nonnegative, but floating-point rounding and the allowed normalization tolerance can produce a tiny negative result near equality. The function does not silently clip it: first inspect normalization and compare with a higher-precision calculation. A large negative value indicates an incorrect formula, invalid inputs, or a numerical failure rather than a new property of KL.
The order here is explicitly target, reference. A library may instead expect log probabilities as its first tensor and ordinary probabilities as its second; check its formula instead of inferring order from an argument name. This program implements only finite discrete distributions. Passing sampled density heights as if they were a normalized probability vector does not compute a continuous KL.
Support is a property of measures
For probability measures P and Q on the same measurable space, the general definition is
The notation means that every measurable set with zero Q probability also has zero P probability. The derivative is a density of P relative to Q, not an ordinary derivative with respect to a coordinate. If both have densities p and q relative to a common reference measure, the formula becomes over that measure. Changes at density values on measure-zero sets do not change the answer. Absolute continuity still does not guarantee the integral is finite. MIT 6.441, Section 1.2, measure formulation and infinite-values note
Take P uniform on and Q uniform on . Their densities are 2 and 1 on P’s interval, so D(P∥Q)=log 2. The reverse divergence is infinite because Q assigns positive probability to , where P assigns none. The shared endpoint is irrelevant. P’s differential entropy is , and the cross-entropy against Q is zero; their difference is still positive. Differential entropy can be negative or undefined, while KL between probability measures is nonnegative and well-defined as an extended value. MIT 6.441, Section 1.3
A one-to-one smooth coordinate change with nonzero Jacobian transforms both densities with the same Jacobian factor; it cancels in their ratio, and substitution preserves KL. Coarse grouping loses information instead. For positive finite joint distributions, expanding the log ratio gives the chain rule
The conditional terms are nonnegative, so retaining only X cannot increase divergence. This original derivation explains why merging two different categories can conceal a mismatch. A histogram KL also depends on the chosen bins and estimation method; it is not automatically the KL between the underlying continuous distributions.
Try to break the wrong interpretation
- Does p=q require entropy zero? Answer: no. For two equal fair binary distributions, KL is zero while entropy and cross-entropy are both log 2 nats.
- With p=(3/4,1/4) and q=(1/2,1/2), a one-observation sample happens to be blue. What is its estimated excess log loss? Answer: log(1/2), about −0.693147 nats. A sampled term may be negative although its population expectation is positive.
- Why does D((1/2,1/2)∥(1,0)) diverge? Answer: the second event has positive target probability but zero reference probability. Reversing the arguments changes that support check and gives log 2.
- Merge red and blue into one category in both toy distributions. What happens? Answer: both become the point mass (1), so KL becomes zero. The grouping has discarded every distinction between them.
Choose what a divergence is allowed to ignore
Variational inference often optimizes one directed KL within a restricted approximating family. Maximum likelihood connects to the other direction through a target-weighted log score. The right direction depends on which expectation is available and which mistakes the model should penalize; swapping arguments changes the problem.
If p is unknown, observations alone do not provide exact values of log p. Replacing p and q with empirical histograms introduces estimation error, and empty bins need care: no observed event does not establish zero population probability. For a finite collection of known distributions, the examples here can be checked exactly or to high precision. For learned continuous models, specifying the measures, supports, estimator, and integration method is part of reporting the result.
Make a prediction, then check
Let p=(1/2,1/2) and q=(1,0). What are KL(p∥q) and KL(q∥p)?
Learning objectives
- Derive KL from excess log loss and prove nonnegativity and equality conditions with Jensen’s inequality.
- Identify direction, missing support, and triangle-inequality failures, distinguishing sampled terms from population divergence.
- Explain the probability-measure definition, negative differential entropy, coordinate invariance, and information loss under coarsening.
Prerequisites & connections
Explore related knowledge →References
- MIT 6.441 — Chapter 1: Information Measures: Entropy and Divergence
Yury Polyanskiy; Yihong Wu · 2016 - Deep Learning — Chapter 3: Probability and Information Theory
Ian Goodfellow; Yoshua Bengio; Aaron Courville · 2016
Version1 · Editorial status: Recorded technical checks completed
View technical check record (AI)
Codex · 2026-09-05 · Codex multi-agent technical check: primary-source verification, derivation and numerical assertions, bilingual comparison, and review by another agent or the parent; no independent human peer review.
- Re-derived Jensen nonnegativity/equality, direction and support conditions, and the finite joint chain rule; checked measure and differential-entropy boundaries.
- Checked every pair of three-category probability vectors with denominator 4 against 80-digit Decimal log ratios, plus entropy decomposition, asymmetry, and the triangle counterexample.
- Checked conditional decomposition and nonincreasing divergence under coarsening using rational joint distributions; integrated piecewise constant densities for negative entropy, infinite reverse KL, and scaling invariance.
- Compared bilingual display math, full code, four answered exercises, and numerical values; tested zero probabilities, nonfinite or unnormalized inputs, and intermediate-ratio overflow.
- The parent reviewed Jensen equality conditions, support, asymmetry and triangle counterexamples, measure definitions, infinity-subtraction limits and coordinate invariance, and executed chain-rule, coarsening and piecewise-density integral checks.
- The parent executed all 30 new checks and all 55 combined probability/inference tests; bilingual code, display equations, six main anchors, citations and four answered exercises were additionally compared.
Source locations checked:
- MIT 6.441 — Chapter 1: Information Measures: Entropy and Divergence · Sections 1.2–1.3: PDF pp.8–9/printed pp.15–16, Definition 1.4, zero support, Radon–Nikodym derivative, absolute continuity and possible infinity even with P≪Q; PDF p.11/printed p.18 differential entropy warning. Jensen review PDF p.3/printed p.10. Authors verified on MIT lecture-notes page.
- Deep Learning — Chapter 3: Probability and Information Theory · Section 3.13 equations 3.50–3.51, printed pp.72–73: directed expectation, nonnegativity, identity, asymmetry; Figure 3.6 and caption printed p.74 explicitly qualify mode-covering/mode-selection behavior.
Related topics