relative-entropy VS cross-entropy
Cross-entropy H(P, Q) measures the average code length when encoding events from true distribution P using a model distribution Q, while KL divergence (relative entropy) D_KL(P || Q) measures the extra information lost beyond P's intrinsic entropy H(P). Because H(P, Q) = H(P) + D_KL(P || Q) and H(P) does not depend on model parameters, minimizing cross-entropy with respect to Q is mathematically equivalent to minimizing KL divergence.
Study Card: Kullback-Leibler (KL) Divergence vs. Cross-Entropy
Direct Answer
KL Divergence (relative entropy) and Cross-Entropy are linked by a fundamental information-theoretic identity:
where for discrete distributions (true/target) and (predicted/model):
- KL Divergence () quantifies the asymmetric divergence from to —the excess expected information (in bits for , or nats for ) incurred by using instead of , attaining if and only if .
- Cross-Entropy () quantifies the total average information required to encode samples from using a code optimized for .
In supervised learning, the true target distribution is fixed (independent of model parameters of ), so —and for one-hot empirical labels, outright. Therefore, minimizing cross-entropy has the exact same gradient and minimizer as minimizing , without needing to evaluate .
Key Terms
- Probability Distribution: Non-negative weights over outcomes summing to 1.
- Shannon Entropy (): Average intrinsic uncertainty or information content of distribution .
- Relative Entropy (): Asymmetric excess code length when modeling with ; satisfies (Gibbs’ inequality), with in general.
- Cross-Entropy (): Total expected encoding length .
- Loss Function: Cross-entropy serves directly as the standard training objective for classification and autoregressive language modeling.
Example
Suppose the true class distribution over {cat, dog} is and a model predicts . Using natural logs (nats):
- Cross-entropy: .
- Entropy of : .
- KL divergence: .
Similarly, if we evaluate two hard-labeled test images—the first a cat () and the second a dog ()—under predicted distribution , the average cross-entropy across the two samples is .
Code Implementation
import numpy as np
def kl_divergence(p, q):
"""
Calculates Kullback-Leibler divergence D_KL(p || q) in nats.
Uses masking on p > 0 so zero entries (0 * log(0) = 0) avoid divide/log warnings.
"""
p = np.asarray(p, dtype=float)
q = np.asarray(q, dtype=float)
if np.any(p < 0) or np.any(q < 0):
return np.nan
mask = p > 0
if np.any(q[mask] == 0):
return np.inf
return float(np.sum(p[mask] * np.log(p[mask] / q[mask])))
def cross_entropy(p, q):
"""
Calculates cross-entropy H(p, q) in nats.
"""
p = np.asarray(p, dtype=float)
q = np.asarray(q, dtype=float)
if np.any(p < 0) or np.any(q < 0):
return np.nan
mask = p > 0
if np.any(q[mask] == 0):
return np.inf
return float(-np.sum(p[mask] * np.log(q[mask])))
# Example 1
p1 = np.array([0.6, 0.4])
q1 = np.array([0.5, 0.5])
print(f"KL Divergence: {kl_divergence(p1, q1):.6f}")
print(f"Cross Entropy: {cross_entropy(p1, q1):.6f}")
# Example 2: same H(P, Q) = log(2) under uniform Q, but higher D_KL because H(P) is lower
p2 = np.array([0.2, 0.8])
q2 = np.array([0.5, 0.5])
print(f"KL Divergence: {kl_divergence(p2, q2):.6f}")
print(f"Cross Entropy: {cross_entropy(p2, q2):.6f}")
Related Concepts
- Information Theory & Gibbs’ Inequality: guarantees with equality iff .
- Maximum Likelihood Estimation (MLE): Maximizing empirical log-likelihood is identically minimizing empirical cross-entropy and KL divergence .
- Forward vs. Reverse KL: is mode-covering (penalizes wherever ), whereas —used in variational inference—is mode-seeking.
- Distillation & RLHF: KL penalties () and soft-target cross-entropy appear directly when matching probability distributions rather than hard one-hot labels.