Relative Entropy (KL Divergence)
Suppose data come from a distribution , but you believe they come from . How much does the wrong belief cost you? The relative entropy or Kullback-Leibler divergence measures it in bits: the extra code length per symbol when you compress data from with a code designed for .
Definition
with , and if some has but .
import numpy as np
def kl(p, q):
p, q = np.asarray(p, float), np.asarray(q, float)
nz = p > 0
if np.any(q[nz] == 0):
return float("inf")
return float(np.sum(p[nz] * np.log2(p[nz] / q[nz])))
P = [0.5, 0.25, 0.25]; Q = [1 / 3, 1 / 3, 1 / 3]; R = [0.5, 0.5, 0.0]
print("D(P||Q) =", round(kl(P, Q), 4))
print("D(Q||P) =", round(kl(Q, P), 4))
print("D(P||P) =", kl(P, P))
print("D(P||R) =", kl(P, R), " (R gives zero probability to an outcome that happens)")D(P||Q) = 0.085
D(Q||P) = 0.0817
D(P||P) = 0.0
D(P||R) = inf (R gives zero probability to an outcome that happens)
Key properties
- Gibbs' inequality: , with equality only when (Jensen's and Gibbs' Inequalities).
- Not symmetric: in general , so it is not a distance, and it also fails the triangle inequality.
- Convex in the pair .
- Mutual information is a KL divergence: (Mutual Information).
The coding meaning
An ideal code for gives symbol about bits. If the symbols really come from , the average length is the cross-entropy , and
So is exactly the waste caused by using the wrong model (Cross-Entropy).
import numpy as np
P = np.array([0.7, 0.2, 0.1]) # the true source
Q = np.array([1 / 3, 1 / 3, 1 / 3]) # the model used by the code
H = -np.sum(P * np.log2(P))
cross = -np.sum(P * np.log2(Q))
kl = np.sum(P * np.log2(P / Q))
print(f"H(P) = {H:.4f}, H(P,Q) = {cross:.4f}, D(P||Q) = {kl:.4f}, H + D = {H + kl:.4f}")H(P) = 1.1568, H(P,Q) = 1.5850, D(P||Q) = 0.4282, H + D = 1.5850
Forward and reverse KL
When we fit a model to data from , the direction matters:
- Forward is infinite if misses any outcome of , so minimizing it makes cover all of (mean-seeking). Maximum likelihood minimizes this direction (Maximum Likelihood and Cross-Entropy).
- Reverse is infinite if puts mass where has none, so minimizing it makes pick one mode (mode-seeking). Variational inference minimizes this direction.
import numpy as np
x = np.linspace(-6, 6, 1201); dx = x[1] - x[0]
normal = lambda m, s: np.exp(-(x - m)**2 / (2 * s**2)) / (s * np.sqrt(2 * np.pi))
P = 0.5 * normal(-2, 0.6) + 0.5 * normal(2, 0.6) # two modes
def kl(a, b): return float(np.sum(a * np.log(a / b)) * dx) # in nats
best_f = min(((kl(P, normal(m, s)), m, s) for m in np.arange(-3, 3.01, 0.25) for s in np.arange(0.4, 3.01, 0.1)))
best_r = min(((kl(normal(m, s), P), m, s) for m in np.arange(-3, 3.01, 0.25) for s in np.arange(0.4, 3.01, 0.1)))
print(f"forward KL best Gaussian: mean {best_f[1]:+.2f}, std {best_f[2]:.1f} (covers both modes)")
print(f"reverse KL best Gaussian: mean {abs(best_r[1]):.2f} or {-abs(best_r[1]):.2f}, std {best_r[2]:.1f} (sits on one mode)")forward KL best Gaussian: mean +0.00, std 2.1 (covers both modes)
reverse KL best Gaussian: mean 2.00 or -2.00, std 0.6 (sits on one mode)
In software
scipy.stats.entropy(p, q, base=2)returns ;scipy.special.rel_entr(p, q)returns the elementwise terms in nats.torch.nn.KLDivLossexpects log-probabilities for its first argument; read its documentation carefully because the argument order is the reverse of the math notation.- Knowledge distillation trains a small model by minimizing the KL divergence to a large model's softened outputs (Entropy and KL).
Exercises
Exercise 1: Coins
Compute for and .
Answer
About 0.2075 bits.
Solution
.
Exercise 2: Asymmetry
Compute for the same coins. Is it equal to the answer of Exercise 1?
Answer
About 0.1887 bits; no.
Solution
.
Exercise 3: Smoothing (code)
A model estimated from counts gives , but the truth is . The forward KL is infinite. Add-one smoothing on counts gives a new . Compute its KL divergence from .
Answer
About 0.1147 bits.
Solution
import numpy as np
P = np.array([0.5, 0.3, 0.2])
counts = np.array([6, 4, 0]) + 1
Q = counts / counts.sum()
print(np.round(Q, 4), round(float(np.sum(P * np.log2(P / Q))), 4))[0.5385 0.3846 0.0769] 0.1147
Smoothing is the standard cure for zero probabilities in language models and naive Bayes (Naive Bayes).
Test yourself
exactly when…
- P = Q
- P and Q have the same support
- P is uniform
- Q is uniform
Why is KL divergence not a distance?
- It is not symmetric
- It can be negative
- It is always infinite
- It is measured in bits
Maximum-likelihood fitting minimizes…
- forward KL
- reverse KL
- the entropy of Q
- the mutual information