Skip to content
E
Educatum

What is relative entropy?

Curated by Educatum AI teamLast updated:
Basic Concepts
Direct Answer

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 QQ is used to represent a true or reference distribution PP. For discrete and continuous distributions, it is defined as:

DKL(P∥Q)=∑x∈XP(x)log⁡P(x)Q(x),DKL(P∥Q)=∫p(x)log⁡p(x)q(x) dxD_{\text{KL}}(P \parallel Q) = \sum_{x \in \mathcal{X}} P(x) \log \frac{P(x)}{Q(x)}, \qquad D_{\text{KL}}(P \parallel Q) = \int p(x) \log \frac{p(x)}{q(x)} \, dx

with the conventions 0log⁡0q=00 \log \frac{0}{q} = 0 and plog⁡p0=+∞p \log \frac{p}{0} = +\infty for p>0p > 0. By Gibbs’ inequality, DKL(P∥Q)≥0D_{\text{KL}}(P \parallel Q) \ge 0, with equality if and only if P=QP = Q almost everywhere. Because DKL(P∥Q)≠DKL(Q∥P)D_{\text{KL}}(P \parallel Q) \neq D_{\text{KL}}(Q \parallel P) and it violates the triangle inequality, KL divergence is not a true distance metric.

Relative entropy connects directly to cross-entropy H(P,Q)H(P, Q) and Shannon entropy H(P)H(P):

H(P,Q)=−∑xP(x)log⁡Q(x)=H(P)+DKL(P∥Q)H(P, Q) = -\sum_x P(x) \log Q(x) = H(P) + D_{\text{KL}}(P \parallel Q)

When PP is fixed (e.g., empirical training labels), minimizing cross-entropy with respect to QQ is mathematically identical to minimizing DKL(P∥Q)D_{\text{KL}}(P \parallel Q).

Key Terms

  • Entropy (H(P)H(P)): Expected information content (uncertainty) of samples drawn from PP.
  • Cross-Entropy (H(P,Q)H(P, Q)): Average code length when encoding samples from PP using a code optimized for QQ.
  • Asymmetry (Forward vs. Reverse KL): Minimizing forward KL DKL(P∥Q)D_{\text{KL}}(P \parallel Q) is mode-covering (mean-seeking) because QQ must place mass everywhere P>0P > 0 to avoid infinite penalty; minimizing reverse KL DKL(Q∥P)D_{\text{KL}}(Q \parallel P) (used in variational inference) is mode-seeking (zero-forcing) because QQ avoids regions where P≈0P \approx 0.
  • 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 PP are bimodal with peaks at 20 and 50, while a simplified Gaussian model QQ places its peak at 35. Under forward KL DKL(P∥Q)D_{\text{KL}}(P \parallel Q), QQ suffers a huge penalty if it assigns near-zero density at 20 or 50, forcing QQ to spread broadly across both modes. Under reverse KL DKL(Q∥P)D_{\text{KL}}(Q \parallel P), QQ 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())}")
  • Cross-Entropy Loss: Standard classification objective equal to H(P)+DKL(P∥Q)H(P) + D_{\text{KL}}(P \parallel Q), differing from KL only by the constant data entropy H(P)H(P).
  • Jensen–Shannon Divergence (JSD): Symmetrized, bounded (0≤JSD≤ln⁡20 \le \text{JSD} \le \ln 2) divergence defined via M=12(P+Q)M = \frac{1}{2}(P + Q) as 12DKL(P∥M)+12DKL(Q∥M)\frac{1}{2}D_{\text{KL}}(P \parallel M) + \frac{1}{2}D_{\text{KL}}(Q \parallel M); its square root is a true metric.
  • Mutual Information: Quantifies statistical dependence between variables as I(X;Y)=DKL(P(X,Y)∥P(X)P(Y))I(X; Y) = D_{\text{KL}}(P(X, Y) \parallel P(X)P(Y)).
  • RLHF / Policy Regularization: Modern alignment methods (PPO, GRPO) penalize DKL(πθ∥πref)D_{\text{KL}}(\pi_\theta \parallel \pi_{\text{ref}}) to keep the fine-tuned policy close to the reference language model.
View all →

Try keywords like RoPE, FlashAttention, DPO, or Blind 75.