What is relative entropy?
Relative entropy, commonly known as Kullback-Leibler (KL) divergence, quantifies how one probability distribution Q diverges from a reference distribution P, measuring the extra expected bits or nats required when coding samples from P using Q. KL divergence is always non-negative and equals zero if and only if P and Q match almost everywhere, but it is asymmetric and diverges to infinity whenever Q assigns zero probability to an event with positive probability under P. It links cross-entropy to entropy and underpins variational inference, VAEs, and policy-gradient regularization.
Study Card: What is Relative Entropy (Kullback-Leibler Divergence)
Direct Answer
Relative entropy—also called Kullback–Leibler (KL) divergence—measures how much information is lost when an approximating distribution is used to represent a true or reference distribution . For discrete and continuous distributions, it is defined as:
with the conventions and for . By Gibbs’ inequality, , with equality if and only if almost everywhere. Because and it violates the triangle inequality, KL divergence is not a true distance metric.
Relative entropy connects directly to cross-entropy and Shannon entropy :
When is fixed (e.g., empirical training labels), minimizing cross-entropy with respect to is mathematically identical to minimizing .
Key Terms
- Entropy (): Expected information content (uncertainty) of samples drawn from .
- Cross-Entropy (): Average code length when encoding samples from using a code optimized for .
- Asymmetry (Forward vs. Reverse KL): Minimizing forward KL is mode-covering (mean-seeking) because must place mass everywhere to avoid infinite penalty; minimizing reverse KL (used in variational inference) is mode-seeking (zero-forcing) because avoids regions where .
- Variational Inference & VAEs: Minimize reverse KL (equivalently maximizing the ELBO) to fit tractable approximate posteriors and regularize latent distributions toward a prior.
Example
Suppose true customer ages are bimodal with peaks at 20 and 50, while a simplified Gaussian model places its peak at 35. Under forward KL , suffers a huge penalty if it assigns near-zero density at 20 or 50, forcing to spread broadly across both modes. Under reverse KL , is heavily penalized if it puts density in the low-probability valley at 35, so it tends to lock tightly onto a single mode instead.
Code Implementation
import numpy as np
from scipy.special import kl_div, rel_entr
def relative_entropy(p, q):
"""
Compute KL(P || Q) = sum_i p_i * log(p_i / q_i) in nats for discrete distributions.
Note: scipy.special.kl_div(p, q) equals rel_entr(p, q) - p + q; both sum to the same
value when sum(p) == sum(q) == 1, while rel_entr directly evaluates p * log(p / q).
"""
p = np.asarray(p, dtype=float)
q = np.asarray(q, dtype=float)
if not (np.isclose(p.sum(), 1.0) and np.isclose(q.sum(), 1.0)):
raise ValueError("p and q must each sum to 1.")
return float(np.sum(rel_entr(p, q)))
p = np.array([0.2, 0.3, 0.1, 0.4])
q1 = np.array([0.3, 0.2, 0.2, 0.3])
q2 = np.array([0.25, 0.25, 0.25, 0.25])
print(f"KL(P || P) = {relative_entropy(p, p):.6f}")
print(f"KL(P || Q1) = {relative_entropy(p, q1):.6f}")
print(f"KL(P || Q2 uniform) = {relative_entropy(p, q2):.6f}")
# Verify asymmetry: KL(A || B) != KL(B || A)
a = np.array([0.9, 0.1])
b = np.array([0.2, 0.8])
print(f"KL(A || B) = {relative_entropy(a, b):.6f} vs KL(B || A) = {relative_entropy(b, a):.6f}")
print(f"Matches scipy.special.kl_div sum for normalized inputs: {np.isclose(relative_entropy(a, b), kl_div(a, b).sum())}")
Related Concepts
- Cross-Entropy Loss: Standard classification objective equal to , differing from KL only by the constant data entropy .
- Jensen–Shannon Divergence (JSD): Symmetrized, bounded () divergence defined via as ; its square root is a true metric.
- Mutual Information: Quantifies statistical dependence between variables as .
- RLHF / Policy Regularization: Modern alignment methods (PPO, GRPO) penalize to keep the fine-tuned policy close to the reference language model.