AI Knowledge Tree

KL divergence and cross-entropy

Define KL divergence, prove it is nonnegative, and connect cross-entropy to maximum likelihood.

Training a classifier means making a predicted distribution match a true one. The gap between two distributions is measured by the KL divergence, and the quantity actually minimized in practice, cross-entropy, differs from it only by a constant. Minimizing cross-entropy turns out to be exactly maximum likelihood.

Cross-entropy

The cross-entropy of a distribution qq relative to pp is the expected surprise of outcomes drawn from pp but scored with qq:

H(p,q)=−∑xp(x)log⁡q(x)=Ex∼p[−log⁡q(x)].H(p, q) = -\sum_x p(x) \log q(x) = \mathbb{E}_{x \sim p}[-\log q(x)].

It is the average number of bits to encode samples from the true pp using a code optimized for the model qq. If q=pq = p it reduces to the entropy H(p)H(p). Using the wrong code costs extra bits, and that excess is the KL divergence.

KL divergence

The Kullback-Leibler divergence from pp to qq is the cross-entropy minus the entropy[1, 2]:

DKL(p ∥ q)=H(p,q)−H(p)=∑xp(x)log⁡p(x)q(x).D_{\mathrm{KL}}(p \,\|\, q) = H(p, q) - H(p) = \sum_x p(x)\log\frac{p(x)}{q(x)}.

It is the expected log-ratio under pp. It quantifies the penalty for modeling pp with qq instead of the truth.

Nonnegativity (Gibbs' inequality)

Theorem. DKL(p ∥ q)≥0D_{\mathrm{KL}}(p \,\|\, q) \ge 0, with equality if and only if p=qp = q[3].

Proof. Write the divergence with a sign flip and apply Jensen to the concave logarithm:

−DKL(p ∥ q)=∑xp(x)log⁡q(x)p(x)=Ep ⁣[log⁡q(X)p(X)]≤log⁡Ep ⁣[q(X)p(X)].-D_{\mathrm{KL}}(p \,\|\, q) = \sum_x p(x)\log\frac{q(x)}{p(x)} = \mathbb{E}_{p}\!\left[\log\frac{q(X)}{p(X)}\right] \le \log \mathbb{E}_p\!\left[\frac{q(X)}{p(X)}\right].

The expectation inside is ∑xp(x)q(x)p(x)=∑xq(x)=1\sum_x p(x)\frac{q(x)}{p(x)} = \sum_x q(x) = 1, so the bound is log⁡1=0\log 1 = 0. Therefore −DKL≤0-D_{\mathrm{KL}} \le 0, i.e. DKL≥0D_{\mathrm{KL}} \ge 0. Jensen is tight only when q(X)/p(X)q(X)/p(X) is constant, which with both summing to 1 forces p=qp = q. ■\qquad\blacksquare

Asymmetry

KL is not symmetric: DKL(p ∥ q)≠DKL(q ∥ p)D_{\mathrm{KL}}(p \,\|\, q) \neq D_{\mathrm{KL}}(q \,\|\, p) in general, so it is not a distance. The two directions behave differently. DKL(p ∥ q)D_{\mathrm{KL}}(p \,\|\, q) is "mean-seeking": it is huge where pp has mass but qq does not, so minimizing it forces qq to cover all of pp's support. DKL(q ∥ p)D_{\mathrm{KL}}(q \,\|\, p) is "mode-seeking": it lets qq concentrate on one mode. Variational inference minimizes the second; maximum likelihood, the first.

Cross-entropy loss is maximum likelihood

For classification, pp is the one-hot true label and qθq_\theta the model's predicted class probabilities. The per-example cross-entropy is H(p,qθ)=−log⁡qθ(true class)H(p, q_\theta) = -\log q_\theta(\text{true class}). Averaged over a dataset,

1n∑i=1n−log⁡qθ(yi∣xi)=−1n ℓ(θ),\frac{1}{n}\sum_{i=1}^n -\log q_\theta(y_i \mid x_i) = -\frac{1}{n}\,\ell(\theta),

which is the negative average log-likelihood. Minimizing cross-entropy is maximizing likelihood. Since H(p)H(p) is fixed by the data, minimizing cross-entropy also minimizes DKL(p ∥ qθ)D_{\mathrm{KL}}(p \,\|\, q_\theta): the model is pushed toward the true label distribution.

KL divergence is asymmetric: with p fixed, the forward KL(p‖q) and reverse KL(q‖p) trace different curves as q varies, agreeing only at the shared zero q = p.
KL divergence is asymmetric: with p fixed, the forward KL(p‖q) and reverse KL(q‖p) trace different curves as q varies, agreeing only at the shared zero q = p.

Check it on arrays

python · numpy
import numpy as np

rng = np.random.default_rng(14)

def kl(p, q):
    p, q = np.asarray(p, float), np.asarray(q, float)
    mask = p > 0
    return np.sum(p[mask] * np.log(p[mask] / q[mask]))

def cross_entropy(p, q):
    p, q = np.asarray(p, float), np.asarray(q, float)
    mask = p > 0
    return -np.sum(p[mask] * np.log(q[mask]))

def entropy(p):
    p = np.asarray(p, float)
    mask = p > 0
    return -np.sum(p[mask] * np.log(p[mask]))

p = np.array([0.5, 0.3, 0.2])
q = np.array([0.4, 0.4, 0.2])

print("KL(p||q):", round(kl(p, q), 4), " >= 0")
print("KL(p||p):", round(kl(p, p), 4), " == 0")
print("H(p,q) - H(p):", round(cross_entropy(p, q) - entropy(p), 4),
      " == KL(p||q):", round(kl(p, q), 4))
print("asymmetry: KL(q||p) =", round(kl(q, p), 4), "!= KL(p||q)")

# Cross-entropy loss == negative log-likelihood on one-hot labels
logits = rng.normal(size=(5, 3))
probs = np.exp(logits) / np.exp(logits).sum(axis=1, keepdims=True)
labels = rng.integers(0, 3, size=5)
ce = -np.log(probs[np.arange(5), labels]).mean()
print("mean cross-entropy loss:", round(ce, 4))

KL is nonnegative and zero only against itself, the cross-entropy minus entropy identity holds, the two KL directions disagree, and the classification loss is the mean negative log-likelihood.

Exercises

Exercise 1. With p=(0.5,0.5)p = (0.5, 0.5) and q=(0.25,0.75)q = (0.25, 0.75), compute DKL(p ∥ q)D_{\mathrm{KL}}(p \,\|\, q) and DKL(q ∥ p)D_{\mathrm{KL}}(q \,\|\, p) in bits by hand, and confirm they differ.

Solution

Step 1. Forward direction, ∑xp(x)log⁡2p(x)q(x)\sum_x p(x)\log_2 \frac{p(x)}{q(x)}:

DKL(p ∥ q)=0.5log⁡20.50.25+0.5log⁡20.50.75=0.5⋅1+0.5log⁡223.D_{\mathrm{KL}}(p \,\|\, q) = 0.5 \log_2 \frac{0.5}{0.25} + 0.5 \log_2 \frac{0.5}{0.75} = 0.5 \cdot 1 + 0.5 \log_2 \tfrac{2}{3}.

With log⁡223=1−log⁡23≈1−1.585=−0.585\log_2 \tfrac{2}{3} = 1 - \log_2 3 \approx 1 - 1.585 = -0.585, this is 0.5−0.2925≈0.20750.5 - 0.2925 \approx 0.2075 bits.

Step 2. Reverse direction, ∑xq(x)log⁡2q(x)p(x)\sum_x q(x)\log_2 \frac{q(x)}{p(x)}:

DKL(q ∥ p)=0.25log⁡20.250.5+0.75log⁡20.750.5=0.25⋅(−1)+0.75log⁡21.5.D_{\mathrm{KL}}(q \,\|\, p) = 0.25 \log_2 \frac{0.25}{0.5} + 0.75 \log_2 \frac{0.75}{0.5} = 0.25 \cdot (-1) + 0.75 \log_2 1.5.

With log⁡21.5≈0.585\log_2 1.5 \approx 0.585, this is −0.25+0.4387≈0.1887-0.25 + 0.4387 \approx 0.1887 bits.

Step 3. Both are positive, as Gibbs' inequality requires, and 0.2075≠0.18870.2075 \neq 0.1887: KL is not symmetric.

Exercise 2. Show that the cross-entropy H(p,q)H(p, q) is minimized over qq exactly when q=pq = p, and that its minimum value is the entropy H(p)H(p).

Solution

Step 1. Use the identity from the lesson, H(p,q)=H(p)+DKL(p ∥ q)H(p, q) = H(p) + D_{\mathrm{KL}}(p \,\|\, q). The first term H(p)H(p) does not depend on qq, so minimizing H(p,q)H(p, q) over qq is minimizing DKL(p ∥ q)D_{\mathrm{KL}}(p \,\|\, q).

Step 2. By Gibbs' inequality, DKL(p ∥ q)≥0D_{\mathrm{KL}}(p \,\|\, q) \ge 0 with equality if and only if q=pq = p. So the cross-entropy is minimized precisely at q=pq = p.

Step 3. At that minimizer the divergence term vanishes and H(p,q)=H(p)+0=H(p)H(p, q) = H(p) + 0 = H(p). The best a model can do is match the true distribution, and then it pays only the irreducible cost H(p)H(p).

Exercise 3 (code). Sample-estimate the cross-entropy H(p,q)H(p, q) as the mean of −log⁡q(X)-\log q(X) over draws X∼pX \sim p, and confirm it equals H(p)+DKL(p ∥ q)H(p) + D_{\mathrm{KL}}(p \,\|\, q) computed exactly.

Solution
python · numpy
import numpy as np

rng = np.random.default_rng(15)

p = np.array([0.5, 0.3, 0.2])
q = np.array([0.4, 0.4, 0.2])

# Monte Carlo cross-entropy: E_{X~p}[-log q(X)]
X = rng.choice(3, size=2_000_000, p=p)
ce_mc = -np.log(q[X]).mean()

H_p = -(p * np.log(p)).sum()
kl_pq = (p * np.log(p / q)).sum()
ce_exact = H_p + kl_pq

assert np.isclose(ce_mc, ce_exact, atol=2e-3)
print("cross-entropy MC:", round(ce_mc, 4), " H(p)+KL:", round(ce_exact, 4))

The sampled cross-entropy matches H(p)+DKL(p ∥ q)H(p) + D_{\mathrm{KL}}(p \,\|\, q), the decomposition the whole lesson rests on.

The next lesson uses KL to measure how much two variables tell you about each other: mutual information.


References

  1. [1]Cover, T. M., & Thomas, J. A. (2006). Elements of Information Theory (2nd ed.). Wiley. §2.3, relative entropy and cross-entropy. doi:10.1002/047174882X↩
  2. [2]Bishop, C. M. (2006). Pattern Recognition and Machine Learning. Springer. §1.6.1, relative entropy and its link to maximum likelihood.↩
  3. [3]MacKay, D. J. C. (2003). Information Theory, Inference, and Learning Algorithms. Cambridge University Press. §2.6, Gibbs' inequality and nonnegativity of the KL divergence.↩