Skip to main content
© 2026 ePowerAI. All rights reserved.
CoursesContact
eAI
CoursesContact
Week 11: Information Theory for ML
Prob & Stats
01Week 1: Probability Spaces and Events
02Week 2: Random Variables and Distributions
03Week 3: Expectation, Variance, and Covariance
04Week 4: Conditioning and Independence
05Week 5: Bayes' Rule and Generative Classification
06Week 6: Multivariate Gaussians
07Week 7: Laws of Large Numbers and the CLT
08Week 8: Point Estimation — Maximum Likelihood
09Week 9: Bayesian Estimation and MAP
10Week 10: Bias, Variance, and Uncertainty
11Week 11: Information Theory for ML
12Week 12: Exponential Families (lite)
13Week 13: Graphical Models (lite)
14Week 14: Capstone — Probabilistic Language of ML
Week 11· Prob & Stats· ML interface22 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.

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 — no uncertainty, no information needed. A uniform distribution over kkk outcomes has H=log⁡kH = \log kH=logk — 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 — 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#

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 — it forces 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 — it forces 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(f"Asymmetry — these minima are at different q values")
← 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