Skip to main content
© 2026 ePowerAI — free, open courseware. No login required.
CoursesContact
ePOWERAI
CoursesContact
Week 11: Information Theory for ML
Prob & Stats

Foundations

  1. 01Week 1: Probability Spaces and Events
  2. 02Week 2: Random Variables and Distributions
  3. 03Week 3: Expectation, Variance, and Covariance
  4. 04Week 4: Conditioning and Independence
  5. 05Week 5: Bayes' Rule and Generative Classification
  6. 06Week 6: Multivariate Gaussians

Inference

  1. 07Week 7: Laws of Large Numbers and the CLT
  2. 08Week 8: Point Estimation — Maximum Likelihood
  3. 09Week 9: Bayesian Estimation and MAP
  4. 10Week 10: Bias, Variance, and Uncertainty

ML interface

  1. 11Week 11: Information Theory for ML
  2. 12Week 12: Exponential Families (lite)
  3. 13Week 13: Graphical Models (lite)

Capstone

  1. 14Week 14: Capstone — Probabilistic Language of ML
Week 11· Prob & Stats· ML interface8 min read

Week 11: Information Theory for ML

Learning Outcomes
  • Compute Shannon entropy for a discrete distribution
  • Define cross-entropy and KLKullback–Leibler divergence; prove KL≥0\text{KL} \ge 0KL≥0 (Gibbs inequality sketch)
  • Show MLE ≡\equiv≡ minimising KL to the empirical distribution (discrete case)
  • Contrast forward vs reverse KL qualitatively (mode-covering vs mode-seeking)
Prerequisites

Required: Weeks 2–3 (distributions, expectation), Week 8 (MLE). Entropy and KL divergence are the language of variational inference, diffusion models, and RL exploration.

Preview: The ELBOEvidence Lower Bound in Generative Models is a KL-related bound. This week gives you the vocabulary to read those derivations.

  • Also see: Reinforcement Learning Week 7: Policy Gradient and Actor–Critic Methods — entropy bonuses as exploration.

Entropy#

Shannon entropy measures the uncertainty (or information content) of a distribution. For a discrete distribution ppp over outcomes {x1,…,xk}\{x_1, \ldots, x_k\}{x1​,…,xk​}:

H(p)=−∑i=1kp(xi)log⁡p(xi).H(p) = -\sum_{i=1}^k p(x_i) \log p(x_i).H(p)=−i=1∑k​p(xi​)logp(xi​).

Using log⁡2\log_2log2​ gives entropy in bits; using natural log gives nats. In ML, natural log is standard (connection to e-based calculus).

Interpretation: H(p)H(p)H(p) is the minimum average number of bits (or nats) needed to encode a symbol drawn from ppp. A deterministic distribution (p(x1)=1p(x_1) = 1p(x1​)=1, all others 0) has H=0H = 0H=0, meaning no uncertainty and no information needed. A uniform distribution over kkk outcomes has H=log⁡kH = \log kH=logk, the maximum uncertainty. Entropy is always ≥0\ge 0≥0.

Worked example: biased coin. p=0.7p = 0.7p=0.7 for heads, 0.30.30.3 for tails (nats):

H=−[0.7ln⁡(0.7)+0.3ln⁡(0.3)]=−[0.7(−0.357)+0.3(−1.204)]=0.250+0.361=0.611 nats.H = -[0.7 \ln(0.7) + 0.3 \ln(0.3)] = -[0.7(-0.357) + 0.3(-1.204)] = 0.250 + 0.361 = 0.611 \text{ nats}.H=−[0.7ln(0.7)+0.3ln(0.3)]=−[0.7(−0.357)+0.3(−1.204)]=0.250+0.361=0.611 nats.

A fair coin has H=ln⁡2≈0.693H = \ln 2 \approx 0.693H=ln2≈0.693 nats, showing more uncertainty. A deterministic coin (p=1p = 1p=1) has H=0H = 0H=0.

Differential entropy is the continuous analogue (for PDFs), but it lacks some nice properties of discrete entropy (e.g., it can be negative). We focus on the discrete case; KL divergence handles continuous distributions fine.

Cross-entropy and KL divergence#

uniform: high entropy peaked: low entropy entropy measures uncertainty; KL is the cost of being wrong minimising KL(q‖p) is the same as maximising the likelihood

Entropy measures how uncertain a distribution is; KL measures how costly it is to use the wrong one. Minimising KL to the empirical distribution is exactly maximum likelihood, which is why cross-entropy is the default loss for classification.

Cross-entropy H(p,q)H(p, q)H(p,q) measures the average number of bits needed to encode samples from ppp using a code optimised for qqq:

H(p,q)=−∑xp(x)log⁡q(x)=−Ex∼p[log⁡q(x)].H(p, q) = -\sum_x p(x) \log q(x) = -\mathbb{E}_{x \sim p}[\log q(x)].H(p,q)=−x∑​p(x)logq(x)=−Ex∼p​[logq(x)].

KLKullback–Leibler divergence divergence (relative entropy) measures how much extra information is needed when using qqq instead of ppp:

DKL(p∥q)=∑xp(x)log⁡p(x)q(x)=H(p,q)−H(p).D_{\mathrm{KL}}(p \parallel q) = \sum_x p(x) \log\frac{p(x)}{q(x)} = H(p, q) - H(p).DKL​(p∥q)=x∑​p(x)logq(x)p(x)​=H(p,q)−H(p).

KL is not a distance metric: it is asymmetric (DKL(p∥q)≠DKL(q∥p)D_{\mathrm{KL}}(p \parallel q) \ne D_{\mathrm{KL}}(q \parallel p)DKL​(p∥q)=DKL​(q∥p) in general) and does not satisfy the triangle inequality. But it is always ≥0\ge 0≥0, with equality iff p=qp = qp=q.

Gibbs inequality (proof sketch for KL ≥0\ge 0≥0):

Using the inequality ln⁡t≤t−1\ln t \le t - 1lnt≤t−1 for t>0t > 0t>0 (with equality only at t=1t = 1t=1):

−DKL(p∥q)=∑xp(x)ln⁡q(x)p(x)≤∑xp(x)(q(x)p(x)−1)=∑xq(x)−∑xp(x)=1−1=0.-D_{\mathrm{KL}}(p \parallel q) = \sum_x p(x) \ln \frac{q(x)}{p(x)} \le \sum_x p(x) \left(\frac{q(x)}{p(x)} - 1\right) = \sum_x q(x) - \sum_x p(x) = 1 - 1 = 0.−DKL​(p∥q)=x∑​p(x)lnp(x)q(x)​≤x∑​p(x)(p(x)q(x)​−1)=x∑​q(x)−x∑​p(x)=1−1=0.

Thus −DKL≤0-D_{\mathrm{KL}} \le 0−DKL​≤0, so DKL≥0D_{\mathrm{KL}} \ge 0DKL​≥0. The inequality is strict unless p=qp = qp=q everywhere.

KL and MLE#

There is a deep equivalence: maximising likelihood is minimising KL divergence to the empirical distribution.

Let p^\hat pp^​ be the empirical distribution of the data (puts mass 1/n1/n1/n at each observed xix_ixi​). The KL from p^\hat pp^​ to the model pθp_\thetapθ​ is:

DKL(p^∥pθ)=∑xp^(x)log⁡p^(x)pθ(x)=−1n∑i=1nlog⁡pθ(xi)−H(p^).D_{\mathrm{KL}}(\hat p \parallel p_\theta) = \sum_x \hat p(x) \log\frac{\hat p(x)}{p_\theta(x)} = -\frac{1}{n}\sum_{i=1}^n \log p_\theta(x_i) - H(\hat p).DKL​(p^​∥pθ​)=x∑​p^​(x)logpθ​(x)p^​(x)​=−n1​i=1∑n​logpθ​(xi​)−H(p^​).

H(p^)H(\hat p)H(p^​) does not depend on θ\thetaθ, so:

arg⁡min⁡θDKL(p^∥pθ)=arg⁡min⁡θ(−1n∑i=1nlog⁡pθ(xi))=arg⁡max⁡θ∑i=1nlog⁡pθ(xi)=θ^MLE.\arg\min_\theta D_{\mathrm{KL}}(\hat p \parallel p_\theta) = \arg\min_\theta \left(-\frac{1}{n}\sum_{i=1}^n \log p_\theta(x_i)\right) = \arg\max_\theta \sum_{i=1}^n \log p_\theta(x_i) = \hat \theta_{\text{MLE}}.argθmin​DKL​(p^​∥pθ​)=argθmin​(−n1​i=1∑n​logpθ​(xi​))=argθmax​i=1∑n​logpθ​(xi​)=θ^MLE​.

Training a model by MLE is equivalent to finding the model distribution that is "closest" (in forward KL sense) to the empirical data distribution. This is why the negative log-likelihood is called the cross-entropy loss in classification: it is the cross-entropy between the one-hot label distribution and the model's predicted distribution.

Forward vs reverse KL#

Because KL is asymmetric, the direction matters for optimisation behaviour.

Forward KL: DKL(pdata∥qθ)D_{\mathrm{KL}}(p_{\text{data}} \parallel q_\theta)DKL​(pdata​∥qθ​)

This penalises qθq_\thetaqθ​ heavily where pdatap_{\text{data}}pdata​ has mass but qθq_\thetaqθ​ has little, forcing qθq_\thetaqθ​ to cover all regions where data appear. This is mode-covering: the model spreads probability mass across all modes of the data, even if it must put some mass in low-density regions. MLE training uses forward KL implicitly.

Reverse KL: DKL(qθ∥pdata)D_{\mathrm{KL}}(q_\theta \parallel p_{\text{data}})DKL​(qθ​∥pdata​)

This penalises qθq_\thetaqθ​ heavily where qθq_\thetaqθ​ has mass but pdatap_{\text{data}}pdata​ has little, forcing qθq_\thetaqθ​ to avoid regions with no data. This is mode-seeking: the model concentrates on a subset of modes, ignoring others. Variational inference (used in VAEs) minimises reverse KL, which is why VAEs can produce sharp but limited-diversity samples.

Cartoon illustration. Suppose pdatap_{\text{data}}pdata​ is a mixture of two well-separated Gaussians. Forward KL yields a qqq that covers both bumps (even if it puts mass in the gap). Reverse KL yields a qqq that locks onto one bump and ignores the other.

Link to generative models#

This week sets up the information-theoretic vocabulary you need to read about:

  • VAEs: the ELBOEvidence Lower Bound is Eq[log⁡p(x∣z)]−DKL(q(z∣x)∥p(z))\mathbb{E}_q[\log p(x \mid z)] - D_{\mathrm{KL}}(q(z \mid x) \parallel p(z))Eq​[logp(x∣z)]−DKL​(q(z∣x)∥p(z)), a reconstruction term plus a KL regulariser.
  • Diffusion models: the training objective is a weighted sum of denoising score-matching terms, which can be derived from a variational bound on the KL between data and model distributions.
  • RL exploration: entropy bonuses (H(π)H(\pi)H(π)) encourage policies to remain stochastic, preventing premature convergence.

You do not need to derive these now. This course gives you the vocabulary so the derivations are readable when you encounter them.

Exercise · Fill in the blank

Compute D_KL(p || q) in nats for p = [0.8, 0.2] and q = [0.5, 0.5]. Use natural log. Round to 3 decimal places.


Knowledge check#

Question 1 of 4

KL divergence is a proper distance metric (symmetric, satisfies triangle inequality). True or false?

False — KL is asymmetric and does not satisfy triangle inequality
True — KL is a metric
False — KL is symmetric but not a metric
True — but only for discrete distributions

Browser lab#

Compute KL divergence between categorical distributions over a grid of qqq values vs a fixed ppp, and show the asymmetry.

python · runs in browser
import numpy as np
import matplotlib.pyplot as plt

p = np.array([0.7, 0.2, 0.1])

def kl(p, q):
    """KL(p || q) in nats. Assumes q > 0 where p > 0."""
    mask = p > 0
    return np.sum(p[mask] * np.log(p[mask] / q[mask]))

qs = []
kl_forward = []
kl_reverse = []

for a in np.linspace(0.05, 0.9, 30):
    for b in np.linspace(0.05, 0.9, 30):
        c = 1 - a - b
        if c <= 0:
            continue
        q = np.array([a, b, c])
        qs.append(q)
        kl_forward.append(kl(p, q))
        kl_reverse.append(kl(q, p))

qs = np.array(qs)
kl_forward = np.array(kl_forward)
kl_reverse = np.array(kl_reverse)

fig, axes = plt.subplots(1, 3, figsize=(14, 4.5))

sc = axes[0].scatter(qs[:, 0], qs[:, 1], c=kl_forward, cmap="Reds", s=20)
axes[0].scatter(p[0], p[1], color="black", s=100, marker="*", label="p")
axes[0].set_xlabel("q₁"); axes[0].set_ylabel("q₂")
axes[0].set_title("Forward KL(p || q)")
plt.colorbar(sc, ax=axes[0], label="nats")

sc = axes[1].scatter(qs[:, 0], qs[:, 1], c=kl_reverse, cmap="Blues", s=20)
axes[1].scatter(p[0], p[1], color="black", s=100, marker="*", label="p")
axes[1].set_xlabel("q₁"); axes[1].set_ylabel("q₂")
axes[1].set_title("Reverse KL(q || p)")
plt.colorbar(sc, ax=axes[1], label="nats")

axes[2].scatter(kl_forward, kl_reverse, c=qs[:, 0], s=10, alpha=0.7)
axes[2].set_xlabel("KL(p || q)"); axes[2].set_ylabel("KL(q || p)")
axes[2].set_title("KL Asymmetry")
axes[2].plot([0, max(kl_forward)], [0, max(kl_forward)], "k--", alpha=0.3)

plt.tight_layout()
plt.show()

idx_min_fwd = np.argmin(kl_forward)
idx_min_rev = np.argmin(kl_reverse)
print(f"p = {p}")
print(f"min KL(p||q) at q = {np.round(qs[idx_min_fwd], 3)}, value={kl_forward[idx_min_fwd]:.4f}")
print(f"min KL(q||p) at q = {np.round(qs[idx_min_rev], 3)}, value={kl_reverse[idx_min_rev]:.4f}")
print("Both directions bottom out at q ≈ p — the asymmetry is in how steeply each surface penalises moving mass, not in where the minimum sits.")

print("Notice: both surfaces bottom out at the same q ≈ [0.695, 0.197, 0.109] — the asymmetry is in how steeply each one punishes a mismatch.")

Key takeaways#

  • Shannon entropy measures uncertainty: zero for a deterministic distribution, maximal at log⁡k\log klogk for the uniform distribution over kkk outcomes.
  • Cross-entropy is the cost of encoding samples from one distribution with a code built for another; KL divergence is the excess cost, DKL(p∥q)=H(p,q)−H(p)D_{\mathrm{KL}}(p \parallel q) = H(p, q) - H(p)DKL​(p∥q)=H(p,q)−H(p).
  • KL is non-negative and zero only when the distributions match, but it is asymmetric and not a metric.
  • Maximum likelihood is exactly minimising forward KL from the empirical distribution to the model, which is why classification uses the cross-entropy loss.
  • Forward KL is mode-covering; reverse KL is mode-seeking. That asymmetry is why VAEs produce sharp but limited-diversity samples.
  • The ELBO, diffusion training objectives, and reinforcement-learning entropy bonuses are all built from this vocabulary.

Further reading#

  • Thomas M. Cover & Joy A. Thomas, Elements of Information Theory (2nd ed., Wiley, 2006): Chapter 2 is the canonical treatment of entropy, cross-entropy, and KL.
  • David J. C. MacKay, Information Theory, Inference, and Learning Algorithms (Cambridge University Press, 2003): free online; links information theory directly to inference.
  • Christopher M. Bishop, Pattern Recognition and Machine Learning (Springer, 2006): §1.6 gives the ML-facing summary of these quantities.

Reading is free. PDF and ePub unlock with the newsletter. Join once and every lesson opens in this browser.

← Previous
Week 10: Bias, Variance, and Uncertainty
Next →
Week 12: Exponential Families (lite)
On this page
  • Entropy
  • Cross-entropy and KL divergence
  • KL and MLE
  • Forward vs reverse KL
  • Link to generative models
  • Knowledge check
  • Browser lab
  • Key takeaways
  • Further reading