TExcelTAD
Home › Information Theory › Relative Entropy (KL Divergence)

Relative Entropy (KL Divergence)

Suppose data come from a distribution PP, but you believe they come from QQ. How much does the wrong belief cost you? The relative entropy or Kullback-Leibler divergence DKL(P∥Q)D_{\text{KL}}(P \parallel Q) measures it in bits: the extra code length per symbol when you compress data from PP with a code designed for QQ.

Definition

DKL(P∥Q)=∑xP(x)log⁡2P(x)Q(x)D_{\text{KL}}(P \parallel Q) = \sum_x P(x)\log_2 \frac{P(x)}{Q(x)}

with 0log⁡0q=00 \log \frac{0}{q} = 0, and DKL=∞D_{\text{KL}} = \infty if some xx has P(x)>0P(x) > 0 but Q(x)=0Q(x) = 0.

python · try it yourself
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: DKL(P∥Q)≥0D_{\text{KL}}(P \parallel Q) \ge 0, with equality only when P=QP = Q (Jensen's and Gibbs' Inequalities).
  • Not symmetric: in general DKL(P∥Q)≠DKL(Q∥P)D_{\text{KL}}(P \parallel Q) \ne D_{\text{KL}}(Q \parallel P), so it is not a distance, and it also fails the triangle inequality.
  • Convex in the pair (P,Q)(P, Q).
  • Mutual information is a KL divergence: I(X;Y)=DKL(PXY∥PXPY)I(X; Y) = D_{\text{KL}}(P_{XY} \parallel P_X P_Y) (Mutual Information).

The coding meaning

An ideal code for QQ gives symbol xx about log⁡21Q(x)\log_2 \frac{1}{Q(x)} bits. If the symbols really come from PP, the average length is the cross-entropy H(P,Q)H(P, Q), and

H(P,Q)=H(P)+DKL(P∥Q)H(P, Q) = H(P) + D_{\text{KL}}(P \parallel Q)

So DKLD_{\text{KL}} is exactly the waste caused by using the wrong model (Cross-Entropy).

python · try it yourself
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 QQ to data from PP, the direction matters:

  • Forward DKL(P∥Q)D_{\text{KL}}(P \parallel Q) is infinite if QQ misses any outcome of PP, so minimizing it makes QQ cover all of PP (mean-seeking). Maximum likelihood minimizes this direction (Maximum Likelihood and Cross-Entropy).
  • Reverse DKL(Q∥P)D_{\text{KL}}(Q \parallel P) is infinite if QQ puts mass where PP has none, so minimizing it makes QQ pick one mode (mode-seeking). Variational inference minimizes this direction.
python · try it yourself
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 DKL(P∥Q)D_{\text{KL}}(P \parallel Q); scipy.special.rel_entr(p, q) returns the elementwise terms in nats.
  • torch.nn.KLDivLoss expects 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 DKL(P∥Q)D_{\text{KL}}(P \parallel Q) for P=(12,12)P = (\frac{1}{2}, \frac{1}{2}) and Q=(34,14)Q = (\frac{3}{4}, \frac{1}{4}).

Answer

About 0.2075 bits.

Solution

12log⁡21/23/4+12log⁡21/21/4=12(−0.585)+12(1)=0.2075\frac{1}{2}\log_2 \frac{1/2}{3/4} + \frac{1}{2}\log_2 \frac{1/2}{1/4} = \frac{1}{2}(-0.585) + \frac{1}{2}(1) = 0.2075.

Exercise 2: Asymmetry

Compute DKL(Q∥P)D_{\text{KL}}(Q \parallel P) for the same coins. Is it equal to the answer of Exercise 1?

Answer

About 0.1887 bits; no.

Solution

34log⁡232+14log⁡212=0.4387−0.25=0.1887\frac{3}{4}\log_2 \frac{3}{2} + \frac{1}{4}\log_2 \frac{1}{2} = 0.4387 - 0.25 = 0.1887.

Exercise 3: Smoothing (code)

A model estimated from counts gives Q=(0.6,0.4,0)Q = (0.6, 0.4, 0), but the truth is P=(0.5,0.3,0.2)P = (0.5, 0.3, 0.2). The forward KL is infinite. Add-one smoothing on counts (6,4,0)(6, 4, 0) gives a new QQ. Compute its KL divergence from PP.

Answer

About 0.1147 bits.

Solution
python · try it yourself
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

DKL(P∥Q)=0D_{\text{KL}}(P \parallel Q) = 0 exactly when…

  1. P = Q
  2. P and Q have the same support
  3. P is uniform
  4. Q is uniform

Why is KL divergence not a distance?

  1. It is not symmetric
  2. It can be negative
  3. It is always infinite
  4. It is measured in bits

Maximum-likelihood fitting minimizes…

  1. forward KL DKL(Pdata∥Q)D_{\text{KL}}(P_{\text{data}} \parallel Q)
  2. reverse KL DKL(Q∥Pdata)D_{\text{KL}}(Q \parallel P_{\text{data}})
  3. the entropy of Q
  4. the mutual information