Skip to content
E
Educatum

relative-entropy VS cross-entropy

Curated by Educatum AI teamLast updated:
Model EvaluationLoss
Direct Answer

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:

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

where for discrete distributions PP (true/target) and QQ (predicted/model):

H(P)=−∑xP(x)log⁡P(x),H(P,Q)=−∑xP(x)log⁡Q(x),DKL(P∥Q)=∑xP(x)log⁡P(x)Q(x)≥0H(P) = -\sum_{x} P(x)\log P(x), \qquad H(P, Q) = -\sum_{x} P(x)\log Q(x), \qquad D_{\text{KL}}(P \| Q) = \sum_{x} P(x)\log\frac{P(x)}{Q(x)} \ge 0
  • KL Divergence (DKL(P∥Q)D_{\text{KL}}(P \| Q)) quantifies the asymmetric divergence from QQ to PP—the excess expected information (in bits for log⁡2\log_2, or nats for ln⁡\ln) incurred by using QQ instead of PP, attaining 00 if and only if P=QP = Q.
  • Cross-Entropy (H(P,Q)H(P, Q)) quantifies the total average information required to encode samples from PP using a code optimized for QQ.

In supervised learning, the true target distribution PP is fixed (independent of model parameters θ\theta of QθQ_\theta), so ∇θH(P)=0\nabla_\theta H(P) = 0—and for one-hot empirical labels, H(P)=0H(P) = 0 outright. Therefore, minimizing cross-entropy H(P,Qθ)H(P, Q_\theta) has the exact same gradient and minimizer as minimizing DKL(P∥Qθ)D_{\text{KL}}(P \| Q_\theta), without needing to evaluate H(P)H(P).

Key Terms

  • Probability Distribution: Non-negative weights over outcomes summing to 1.
  • Shannon Entropy (H(P)H(P)): Average intrinsic uncertainty or information content of distribution PP.
  • Relative Entropy (DKL(P∥Q)D_{\text{KL}}(P \| Q)): Asymmetric excess code length when modeling PP with QQ; satisfies DKL(P∥Q)≥0D_{\text{KL}}(P \| Q) \ge 0 (Gibbs’ inequality), with DKL(P∥Q)≠DKL(Q∥P)D_{\text{KL}}(P \| Q) \neq D_{\text{KL}}(Q \| P) in general.
  • Cross-Entropy (H(P,Q)H(P, Q)): Total expected encoding length H(P)+DKL(P∥Q)H(P) + D_{\text{KL}}(P \| Q).
  • 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 P=(0.6,0.4)P = (0.6, 0.4) and a model predicts Q=(0.5,0.5)Q = (0.5, 0.5). Using natural logs (nats):

  • Cross-entropy: H(P,Q)=−(0.6log⁡0.5+0.4log⁡0.5)=log⁡2≈0.6931H(P, Q) = -(0.6 \log 0.5 + 0.4 \log 0.5) = \log 2 \approx 0.6931.
  • Entropy of PP: H(P)=−(0.6log⁡0.6+0.4log⁡0.4)≈0.6730H(P) = -(0.6 \log 0.6 + 0.4 \log 0.4) \approx 0.6730.
  • KL divergence: DKL(P∥Q)=H(P,Q)−H(P)≈0.0201D_{\text{KL}}(P \| Q) = H(P, Q) - H(P) \approx 0.0201.

Similarly, if we evaluate two hard-labeled test images—the first a cat (P1=(1,0)P_1 = (1, 0)) and the second a dog (P2=(0,1)P_2 = (0, 1))—under predicted distribution Q=(0.8,0.2)Q = (0.8, 0.2), the average cross-entropy across the two samples is −(log⁡(0.8)+log⁡(0.2))/2≈0.9163-\bigl(\log(0.8) + \log(0.2)\bigr)/2 \approx 0.9163.

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}")
  • Information Theory & Gibbs’ Inequality: DKL(P∥Q)≥0D_{\text{KL}}(P \| Q) \ge 0 guarantees H(P,Q)≥H(P)H(P, Q) \ge H(P) with equality iff Q=PQ = P.
  • Maximum Likelihood Estimation (MLE): Maximizing empirical log-likelihood 1N∑ilog⁡Qθ(xi)\frac{1}{N}\sum_i \log Q_\theta(x_i) is identically minimizing empirical cross-entropy H(P^data,Qθ)H(\hat{P}_{\text{data}}, Q_\theta) and KL divergence DKL(P^data∥Qθ)D_{\text{KL}}(\hat{P}_{\text{data}} \| Q_\theta).
  • Forward vs. Reverse KL: DKL(P∥Q)D_{\text{KL}}(P \| Q) is mode-covering (penalizes Q(x)→0Q(x) \to 0 wherever P(x)>0P(x) > 0), whereas DKL(Q∥P)D_{\text{KL}}(Q \| P)—used in variational inference—is mode-seeking.
  • Distillation & RLHF: KL penalties (DKL(πθ∥πref)D_{\text{KL}}(\pi_\theta \| \pi_{\text{ref}})) and soft-target cross-entropy appear directly when matching probability distributions rather than hard one-hot labels.
View all →

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