Information TheoryComputer Science, Applied · Book 1
0 / 0

Shelves / Information Theory

IT·11

Information in Machine Learning: Cross-Entropy and KL Divergence

The book's ideas as the language of machine learning: cross-entropy, a model's average surprise on real data, which splits exactly into the data's entropy plus the Kullback–Leibler divergence, the price of the wrong model (0.26 extra bits per letter for coding English with French letter frequencies); why KL is never negative, isn't symmetric, and turns mutual information and Blahut–Arimoto into one idea; cross-entropy as the loss that trains classifiers, where one confident mistake can cost 52 bits; perplexity as an effective number of choices; KL as a drift alarm, calibrated against its own noise; which direction to take it, measured on a two-humped distribution; how fast evidence accumulates (Stein's lemma); and, to close, lossy compression's rate–distortion function.

30 topics · ~32 min read · 12-question quiz
Updated Suggest a correction

Start here

What this chapter answers

What does it cost to code data with the wrong model, and how do you measure the difference between two distributions? Why do classifiers and language models minimise cross-entropy, and why does one confident mistake hurt so much? What does a perplexity of 4.4 mean? How can information theory tell you that the data flowing into a system has changed? Why does it matter which way round a divergence is taken? And what's the least information needed to describe something approximately?

Cross-entropy

The surprise of a model

Data comes from a distribution p (the truth), and we use a model q. The model's cross-entropy on the data is its average surprise:

It's what coding the data costs if you build the code from q (chapter 6: arithmetic coding spends log21q(x) bits on x), and in practice it's measured directly: run the model over real data and average log21q(x). Chapter 10's figures (2.13 bits per letter for the blended model) were cross-entropies.

The gap has a name

So cross-entropy splits exactly into two parts:

H(p,q)=H(p)+D(p‖q).

H(p) is the cost no model can avoid, the information in the data itself; D(p‖q) is the extra cost of using q instead of the truth. The lab codes the letters of the English declaration (entropy 4.109 bits per letter) with four models: its own letter frequencies cost 4.109, those of English in the plays 4.149 (0.040 extra), those of the French declaration 4.372 (0.263 extra), and equally likely letters 4.700 (0.591 extra). Each extra cost is exactly the divergence.

Three properties

That's why every model's surprise is at least the entropy (chapter 10's upper bounds) and why the true distribution is the best possible model.

Not symmetric. D(p‖q) and D(q‖p) are usually different: the lab finds 0.263 bits for English letters coded with French frequencies, and 0.155 the other way. Divergence isn't a distance; it measures the cost of a mistake, and mistakes cost differently in each direction.

Infinite for impossible events. If q(x)=0 for some x that p can produce, D(p‖q) is infinite: a model that rules out something that happens pays infinitely when it happens (chapter 10's drill with characters outside a model's alphabet). That's why models are smoothed.

One idea behind several

  • Mutual information is a divergence. I(X;Y) =D(p(x,y)‖p(x)p(y)): how far the joint distribution is from what independence would give. The lab recovers chapter 7's 0.2643 bits between weather and umbrellas this way.
  • Capacity is about divergences. In the Blahut–Arimoto algorithm of chapter 9, each input's score Dx is the divergence between its output distribution and the average output; capacity is the largest achievable average of these divergences.
  • Classification by surprise. Chapter 10's language identifier picked the model with the lowest cross-entropy on a text; since the text's own entropy is the same for every model, that's the model with the smallest divergence from the text's distribution.

Cross-entropy as a loss

Maximum likelihood is minimum cross-entropy

Training a probabilistic model by maximum likelihood means choosing parameters that make the training data most probable, ∏iq(xi). Taking −log2 and dividing by the number of examples turns that into minimising the model's average surprise on the training data, its cross-entropy, which in turn means minimising its divergence from the data's distribution. That's why classifiers, from logistic regression to neural networks, are trained with the cross-entropy loss (also called log loss): for each example, −logq(the right answer).

What log loss rewards

Log loss rewards calibrated confidence: probabilities that match how often the model is right. The lab trains a logistic regression on 398 tumour samples and tests it on 171. It's right 96.5 % of the time and averages 0.155 bits of surprise per case. Then it changes only the model's confidence, keeping every decision the same:

Interactive diagram: Same accuracy, different log loss. It needs JavaScript; the text around it says the same.
  • Five times as confident (each log-odds multiplied by 5): the same 96.5 % accuracy, but 0.523 bits per case, and one mistake costs 52 bits, because the model was nearly certain and wrong.
  • Five times less confident: still 96.5 %, 0.340 bits per case, worst case only 2.39 bits: no disasters, but it never earns the reward for being sure when it's right.
  • Ignoring the input and always saying "benign, 63 %" (the training frequency): 0.954 bits per case, exactly the entropy of the labels. Any useful model must beat this.

Accuracy can't tell the first three apart; cross-entropy can. A mistake made with probability 0.9 costs 3.3 bits, with 0.99 6.6 bits, with 0.999999 almost 20: log loss is unbounded, which makes models pay for overconfidence and is why its average can be dominated by a few confident errors.

Training and held-out cross-entropy

The cross-entropy a model reaches on its training data is biased low (chapter 7), so models are compared on held-out data. Minimising training cross-entropy without limit memorises the training set; regularisation, early stopping and smoothing all exist to keep the held-out cross-entropy low instead.

Perplexity

Language models report their cross-entropy as a perplexity, 2H(p,q): a model with perplexity k is as uncertain, on average, as if it were choosing uniformly among k options at each step. The lab measures the blended models of chapter 10 on 20,000 symbols of training text and 20,000 of unseen text:

Letters of context Training perplexity Unseen perplexity
none 16.6 17.0
1 10.2 10.4
3 4.8 5.3
5 3.0 4.4
7 2.1 5.1

Guessing uniformly among the 27 symbols is perplexity 27. With five letters of context, the model's uncertainty on unseen text is like choosing among 4.4 symbols; with seven, it looks like 2.1 on its training text but 5.1 on new text, the overfitting of chapter 7 in the units language-model papers use. Perplexity grows exponentially with cross-entropy, so a small drop in bits is a large drop in perplexity; comparisons are only meaningful on the same text, with the same symbols (letters, words or sub-word tokens).

Divergence as an alarm

Systems that learn from data assume that tomorrow's data looks like yesterday's. A practical check: compare the distribution of each input over a recent window with a reference distribution, using D(window‖reference), and raise an alarm when it jumps.

Two things make it work. First, sampling noise: even data from the reference distribution gives a positive divergence in a finite window, about k−12nln2 bits for k categories and n samples (chapter 4's bias again). Second, real data varies naturally. The lab compares windows of 2,000 letters from the plays with the letter frequencies of an earlier part: ten normal windows give 0.021 to 0.043 bits, two to five times the 0.009 that independent sampling would explain, because different scenes use different words. When the stream switches to French, the divergence jumps to 0.196 to 0.247. So thresholds must be calibrated on normal data, not taken from formulas, and the jump, not the level, is the signal. (Many monitoring tools use the symmetric "population stability index" or the Jensen–Shannon divergence, both built from KL.)

Which way round?

When a model q must approximate a complicated p, the direction of the divergence decides what kind of mistake is tolerated.

  • D(p‖q) averages over p: it's large wherever p has probability that q misses. Minimising it makes q cover everything p can do. Maximum likelihood minimises this direction.
  • D(q‖p) averages over q: it's large wherever q puts probability that p doesn't have. Minimising it makes q stay inside p, even if that means ignoring parts of it. Variational inference, widely used to approximate complicated posterior distributions, minimises this direction because it's the one that can be computed.

The lab fits a single bell curve to a distribution with two separate bumps, at −3 and +3. Minimising D(p‖q) gives a wide curve centred at 0 (width 3.15), covering both bumps and putting most of its probability in the empty middle. Minimising D(q‖p) gives a narrow curve on one bump (centre +3, width 1.00), ignoring the other entirely, at a divergence of 0.994 bits, about one bit, the information in "which bump?". Neither is wrong; they answer different questions, and choosing between them is part of designing a model.

How fast evidence accumulates

Suppose you must decide whether data comes from p or q (English or French, a fair die or a loaded one). Each observation x moves the evidence by log2p(x)q(x) bits towards p, Turing and Good's "weight of evidence". If the data really comes from p, each observation adds D(p‖q) bits on average.

So divergence is the rate at which evidence piles up. It explains chapter 10's language identification: each English letter carries about 0.26 bits of evidence against French from letter frequencies alone, and far more with context (an English model scored English text about 2.8 bits per character better than a French one), so 20 characters were enough to decide 99.4 % of the time. Sanov's theorem says the same about rare events: the chance that n samples from q look as if they came from p is about 2−nD(p‖q).

Lossy compression: the other side of the coin

Chapters 5 and 6 compressed without loss. Images, sound and video are compressed lossily: some error is accepted to save bits. Shannon (1959) asked how many bits are needed if the reconstruction may differ from the original by a given average distortion d. The answer, the rate–distortion function R(d), is a minimum of mutual information, so this book's tools answer it. For random bits, where distortion is the fraction of bits allowed to be wrong,

R(d)=1−h(d) bits per bit, for d≤12:

allowing 10 % of bits to be wrong needs only 0.531 bits per bit, the same number as a channel that flips 10 % of bits carries (chapter 9). That's no coincidence: describing a source within distortion d and communicating through noise are mirror images, and the Blahut–Arimoto algorithm computes both. Every image and video codec works somewhere above its source's R(d) curve.

Lab: models, losses and drift

Python
"""kl.py: entropy, cross-entropy and Kullback-Leibler divergence, in bits, for chapter 11's lab."""
import math
from collections import Counter

def entropy(p):
    return -sum(x * math.log2(x) for x in p.values() if x > 0)

def cross_entropy(p, q):
    """Average surprise, in bits, of data from p coded with a model q."""
    return -sum(x * math.log2(q[k]) for k, x in p.items() if x > 0)

def kl(p, q):
    """D(p || q): the extra bits per symbol for using q when the data comes from p."""
    return sum(x * math.log2(x / q[k]) for k, x in p.items() if x > 0)

def distribution(items, alphabet=None, smooth=0.0):
    """Relative frequencies, optionally with `smooth` added to every symbol of `alphabet`."""
    c = Counter(items)
    keys = alphabet if alphabet is not None else c.keys()
    total = sum(c[k] + smooth for k in keys)
    return {k: (c[k] + smooth) / total for k in keys}

Experiment 1: the cost of the wrong model

Python
import re
from pathlib import Path
from kl import entropy, cross_entropy, kl, distribution

def letters(path, enc):
    return re.sub(r"[^a-z]", "", Path(path).read_bytes().decode(enc, errors="ignore").lower())
eng = letters("data/udhr/English-Latin1", "latin-1")
fra = letters("data/udhr/French_Francais-Latin1", "latin-1")
plays = letters("data/shakespeare.txt", "utf-8")
az = "abcdefghijklmnopqrstuvwxyz"
P = {"English (declaration)": distribution(eng, az, 0.5), "French (declaration)": distribution(fra, az, 0.5),
     "English (the plays)": distribution(plays, az, 0.5), "every letter equally likely": {a: 1 / 26 for a in az}}
data = P["English (declaration)"]
print(f"letters of the English declaration: entropy H(p) = {entropy(data):.4f} bits per letter\n")
print(f"{'coded with the letter frequencies of':<32}{'cross-entropy':>14}{'H(p) + D(p||q)':>16}{'D(p||q)':>9}")
for name, q in P.items():
    print(f"{name:<32}{cross_entropy(data, q):>14.4f}{entropy(data) + kl(data, q):>16.4f}{kl(data, q):>9.4f}")
fr, en = P["French (declaration)"], P["English (declaration)"]
print(f"\nD(English || French) = {kl(en, fr):.4f}, D(French || English) = {kl(fr, en):.4f}: not symmetric")

# Chapter 7's weather and umbrellas: mutual information is the divergence from independence
joint = {("rain", "umb"): 50 / 365, ("rain", "none"): 10 / 365, ("dry", "umb"): 30 / 365, ("dry", "none"): 275 / 365}
pw = {"rain": 60 / 365, "dry": 305 / 365}; pu = {"umb": 80 / 365, "none": 285 / 365}
indep = {(w, u): pw[w] * pu[u] for w, u in joint}
print(f"D(joint || product of marginals) = {kl(joint, indep):.4f} bits = chapter 7's I(weather; umbrella)")
Text
letters of the English declaration: entropy H(p) = 4.1091 bits per letter

coded with the letter frequencies of cross-entropy  H(p) + D(p||q)  D(p||q)
English (declaration)                   4.1091          4.1091   0.0000
French (declaration)                    4.3724          4.3724   0.2634
English (the plays)                     4.1487          4.1487   0.0397
every letter equally likely             4.7004          4.7004   0.5914

D(English || French) = 0.2634, D(French || English) = 0.1547: not symmetric
D(joint || product of marginals) = 0.2643 bits = chapter 7's I(weather; umbrella)

Every cross-entropy equals the entropy plus the divergence. The plays' English frequencies are close (0.040 extra bits), French ones farther (0.263), uniform farthest (0.591). The divergence isn't symmetric (0.263 against 0.155), and mutual information is a divergence (0.2643 bits, chapter 7's figure).

Experiment 2: log loss in a classifier

Python
import math
import numpy as np
from sklearn.datasets import load_breast_cancer
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler

X, y = load_breast_cancer(return_X_y=True)
Xtr, Xte, ytr, yte = train_test_split(X, y, test_size=0.3, random_state=11, stratify=y)
scale = StandardScaler().fit(Xtr)
model = LogisticRegression(max_iter=5000).fit(scale.transform(Xtr), ytr)
z = model.decision_function(scale.transform(Xte))           # the model's log-odds for each test case

def report(name, z):
    sign = np.where(yte == 1, 1.0, -1.0)                    # +1 if class 1 happened, -1 if class 0
    bits = np.logaddexp(0, -sign * z) / np.log(2)           # -log2 P(what happened), computed without rounding to 0 or 1
    print(f"{name:<34}{np.mean((z > 0) == yte):>9.3f}{bits.mean():>11.4f}{bits.max():>12.2f}")

print(f"{len(ytr)} training and {len(yte)} test cases (tumour samples, benign or malignant)\n")
print(f"{'model':<34}{'accuracy':>9}{'bits/case':>11}{'worst case':>12}")
report("logistic regression", z)
report("same, 5 times as confident", 5 * z)
report("same, 5 times less confident", z / 5)
report("always 'benign, 63 %'", np.full_like(z, math.log(0.627 / 0.373)))
print(f"\none confident mistake costs: p = 0.9 wrong {-math.log2(0.1):.2f} bits, 0.99 wrong {-math.log2(0.01):.2f}, 0.999999 wrong {-math.log2(1e-6):.2f}")
Text
398 training and 171 test cases (tumour samples, benign or malignant)

model                              accuracy  bits/case  worst case
logistic regression                   0.965     0.1550       10.39
same, 5 times as confident            0.965     0.5228       51.97
same, 5 times less confident          0.965     0.3400        2.39
always 'benign, 63 %'                 0.626     0.9539        1.42

one confident mistake costs: p = 0.9 wrong 3.32 bits, 0.99 wrong 6.64, 0.999999 wrong 19.93

Three models with identical decisions and identical accuracy (96.5 %) score 0.155, 0.523 and 0.340 bits per case: cross-entropy rewards calibrated confidence and punishes overconfidence, up to 52 bits for one confident mistake. Ignoring the input costs 0.954 bits, the labels' entropy.

Experiment 3: perplexity

Python
import math, re
from pathlib import Path
from real import Blend

text = re.sub(r"[^a-z]+", " ", Path("data/shakespeare.txt").read_text().lower())
cut = int(len(text) * 0.9)
alphabet = sorted(set(text))
train_part, test_part = text[cut - 20_000:cut], text[cut:cut + 20_000]
print(f"{'context':>8}{'training text':>26}{'unseen text':>26}")
print(f"{'':>8}{'bits':>13}{'perplexity':>13}{'bits':>13}{'perplexity':>13}")
for K in (0, 1, 2, 3, 5, 7):
    m = Blend(alphabet, K); m.train(text[:cut])
    row = []
    for start, part in ((cut - 20_000, train_part), (cut, test_part)):
        bits = -sum(math.log2(m.probs(text[start + i - K:start + i])[part[i]]) for i in range(len(part))) / len(part)
        row += [bits, 2 ** bits]
    print(f"{K:>8}" + "".join(f"{v:>13.3f}" for v in row))
print(f"\nguessing uniformly among the {len(alphabet)} symbols: perplexity {len(alphabet)}, {math.log2(len(alphabet)):.3f} bits")
Text
 context             training text               unseen text
                 bits   perplexity         bits   perplexity
       0        4.056       16.631        4.084       16.957
       1        3.352       10.212        3.379       10.400
       2        2.761        6.777        2.799        6.959
       3        2.257        4.779        2.400        5.280
       5        1.587        3.004        2.130        4.378
       7        1.062        2.087        2.349        5.094

guessing uniformly among the 27 symbols: perplexity 27, 4.755 bits

Perplexity is 2bits. On unseen text the best model, with five letters of context, is as uncertain as a choice among 4.4 symbols; with seven letters, training perplexity keeps falling (2.1) while unseen perplexity rises (5.1).

Experiment 4: divergence as a drift alarm

Python
import math, re
from pathlib import Path
from kl import kl, distribution

az = "abcdefghijklmnopqrstuvwxyz"
plays = re.sub(r"[^a-z]", "", Path("data/shakespeare.txt").read_text().lower())
french = re.sub(r"[^a-z]", "", Path("data/udhr/French_Francais-Latin1").read_bytes().decode("latin-1").lower())
reference = distribution(plays[:200_000], az, 0.5)             # what "normal" looked like
window = 2_000
stream = plays[200_000:200_000 + 10 * window] + french[:3 * window]   # ten normal windows, then the input changes
floor = (len(az) - 1) / (2 * window * math.log(2))
print(f"each window {window:,} letters; KL expected from sampling noise alone: about {floor:.4f} bits\n")
print(f"{'window':>7}{'D(window || reference)':>25}")
for w in range(len(stream) // window):
    d = kl(distribution(stream[w * window:(w + 1) * window], az, 0.5), reference)
    print(f"{w + 1:>7}{d:>25.4f}  {'ALERT' if d > 5 * floor else ''}")
Text
each window 2,000 letters; KL expected from sampling noise alone: about 0.0090 bits

 window   D(window || reference)
      1                   0.0206  
      2                   0.0341  
      3                   0.0312  
      4                   0.0327  
      5                   0.0249  
      6                   0.0269  
      7                   0.0322  
      8                   0.0242  
      9                   0.0428  
     10                   0.0380  
     11                   0.1962  ALERT
     12                   0.2470  ALERT
     13                   0.2187  ALERT

Normal windows sit at 0.021 to 0.043 bits, above the 0.009 that sampling alone would give, because text varies from scene to scene; switching to French raises the divergence to about 0.2, five to ten times the normal level.

Experiment 5: which way round

Python
import math
import numpy as np

x = np.linspace(-10, 10, 4001); dx = x[1] - x[0]
normal = lambda m, s: np.exp(-(x - m) ** 2 / (2 * s * s)) / (s * math.sqrt(2 * math.pi))
p = 0.5 * normal(-3, 1) + 0.5 * normal(3, 1)                 # the truth: two separate bumps
def D(a, b):
    a, b = np.maximum(a, 1e-300), np.maximum(b, 1e-300)
    return float(np.sum(a * np.log2(a / b)) * dx)

best = {}
for name, f in (("D(p || q): penalises q for missing where p has mass", lambda q: D(p, q)),
                ("D(q || p): penalises q for putting mass where p has none", lambda q: D(q, p))):
    score, m, s = min((f(normal(m, s)), m, s) for m in np.arange(-4, 4.01, 0.1) for s in np.arange(0.5, 5.01, 0.05))
    print(f"{name}\n  best single bell curve: centre {m:+.1f}, width {s:.2f}, divergence {score:.3f} bits")
Text
D(p || q): penalises q for missing where p has mass
  best single bell curve: centre +0.0, width 3.15, divergence 0.667 bits
D(q || p): penalises q for putting mass where p has none
  best single bell curve: centre +3.0, width 1.00, divergence 0.994 bits

Covering (D(p‖q)) gives a wide curve over both bumps; staying inside (D(q‖p)) gives a narrow one on a single bump, at a cost of about one bit, the bump it ignores.

Worked examples

A loaded die

Log loss by hand

Perplexity and bits

Exercises

Practice

  1. p=(0.5,0.5) and q=(0.9,0.1). Compute H(p,q), D(p‖q) and D(q‖p).
  2. Why is D(p‖q)=0 only when p=q?
  3. A model gives probability 0 to an event that happens once in a million. What's its divergence from the truth?
  4. A classifier's log loss is 0.3 bits per example, and the labels' entropy is 0.9 bits. What does that say about the classifier?
  5. Convert a perplexity of 20 into bits.
  6. Which direction of KL does maximum likelihood minimise?
  7. What's R(d) for random bits with d=0.5, and why?
Answers
  1. H(p,q) =12log210.9+12log210≈0.076+1.661 =1.737; D(p‖q) =1.737−1 =0.737; D(q‖p) =0.9log21.8+0.1log20.2≈0.763−0.232 =0.531.
  2. Gibbs' inequality: equality in lnu≤u−1 needs u=1, that is q(x)=p(x) everywhere p is positive, and then q has no probability left for anything else.
  3. Infinite: the model pays log210 when the event happens.
  4. It removes 0.9−0.3=0.6 bits of the labels' uncertainty per example: it's informative, and its divergence from the truth is at most 0.3 bits.
  5. log220≈4.32 bits.
  6. D(data‖model), the covering direction.
  7. 0: if half the bits may be wrong, you can send nothing and guess, and on average half your guesses are right.

Harder

  1. Show that I(X;Y) =D(p(x,y)‖p(x)p(y)) from the definitions.
  2. Explain why minimising cross-entropy on training data can make held-out cross-entropy worse, using chapter 7's language.
  3. A drift monitor compares 100-sample windows of a feature with 20 categories. What divergence should normal windows show from sampling alone? What does that imply for the window size?
  4. In the lab's two-bump example, explain why D(q‖p) at its minimum is about 1 bit.
  5. Show that Stein's lemma predicts about how many letters chapter 10's language identifier needs, using only letter frequencies (0.26 bits per letter between English and French), to reach odds of a million to one.
Answers
  1. I(X;Y) =H(X)+H(Y)−H(X,Y) =∑p(x,y)[log21p(x)+log21p(y)−log21p(x,y)] =∑p(x,y)log2p(x,y)p(x)p(y), which is the divergence of the joint from the product.
  2. Training cross-entropy measures surprise on data the model has already seen; minimising it without limit lets the model put probability exactly where the training examples are, memorising accidents of the sample. New data then lands where the model has little probability, so held-out surprise rises: overfitting, as with chapter 7's seven-letter contexts (perplexity 2.1 on training text, 5.1 on unseen).
  3. About 20−12×100ln2≈0.137 bits, large compared with many real shifts; windows must be much bigger (at 5,000 samples, about 0.0027) or thresholds will be dominated by noise. Calibrate on normal windows either way.
  4. The best q sits on one bump and matches it closely, so where q has probability, p is about half of q (the other half of p is in the other bump): log2qp≈log22 =1 bit everywhere q matters.
  5. A million to one is about 20 bits of evidence; at 0.26 bits per letter, about 77 letters. With context models the evidence comes much faster (2 to 3 bits per character in the exercises' P4), which is why 20 characters sufficed there.

Challenge

  1. Show that for a binary classifier, log loss is minimised, for each input, by predicting the true conditional probability of the class, and explain why accuracy has no such property.
Discussion

For an input where the true probability of class 1 is π, predicting q gives expected log loss πlog21q+(1−π)log211−q =H(π,q), which by Gibbs' inequality is smallest exactly at q=π, with the minimum h(π). So log loss is a proper scoring rule: honesty about uncertainty is optimal. Accuracy only checks whether q>12 agrees with the outcome: any q on the right side of 12 scores the same, so it can't reward calibration, and a model can't improve its expected accuracy by reporting its true beliefs. That's why probabilistic models are trained and compared with cross-entropy (or other proper scores, such as the Brier score), and accuracy is reported alongside.

In real life

Misconceptions and limits

The model to keep

Common misconceptions

Misconception What's actually true Where it's shown
"KL divergence is a distance between distributions." It isn't symmetric: 0.263 bits one way, 0.155 the other. Experiment 1
"Cross-entropy and KL measure different things." Cross-entropy is entropy plus KL, exactly. Experiment 1
"Two models with the same accuracy are equally good." 96.5 % each, but 0.155, 0.340 and 0.523 bits per case. Experiment 2
"A confident model is a better model." Five times more confident: one mistake cost 52 bits. Experiment 2
"Lower training perplexity means a better model." Seven letters: training perplexity 2.1, unseen 5.1. Experiment 3
"Any positive divergence from the reference means drift." Normal windows showed 0.02 to 0.04 bits; calibrate first. Experiment 4
"Minimising KL gives the same answer either way round." One direction covers both bumps, the other picks one. Experiment 5
"Lossy compression is beyond information theory." Rate–distortion: 10 % wrong bits needs 0.531 bits per bit. Lossy compression

Limits and trade-offs

  • Divergences need probabilities everywhere. Estimating KL from samples is biased and unstable when categories are rare, and infinite when a model gives zero probability; smoothing, binning choices and estimators matter as much as the formula.
  • Cross-entropy measures probability, not usefulness. A model can have good log loss and still make costly mistakes in the cases that matter most; decisions need costs, not just probabilities.
  • Continuous data needs care. For continuous variables KL is well defined, but estimating it from samples is hard, and in high dimensions it's often replaced by bounds or by other divergences.

Revision sheet

Key ideas

  • Cross-entropy H(p,q) =∑plog21q: a model's average surprise; the code length using q.
  • KL divergence D(p‖q) =∑plog2pq =H(p,q)−H(p): the cost of the wrong model.
  • Gibbs' inequality: D≥0, zero only for p=q; not symmetric; infinite if q rules out what happens.
  • Mutual information =D(p(x,y)‖p(x)p(y)).
  • Log loss: maximum likelihood = minimum cross-entropy; a proper scoring rule; unbounded for confident mistakes.
  • Perplexity =2H(p,q): effective number of choices.
  • Drift: D(window‖reference), with a noise floor of about k−12nln2 and natural variation; calibrate.
  • Direction: D(p‖q) covers (maximum likelihood); D(q‖p) stays inside (variational inference).
  • Evidence: D(p‖q) bits per observation on average; Stein's lemma, Sanov's theorem.
  • Rate–distortion: R(d)=1−h(d) for random bits.

Glossary

  • Cross-entropy: the average surprise of a model q on data from p, ∑xp(x)log21q(x).
  • Kullback–Leibler divergence: D(p‖q) =∑xp(x)log2p(x)q(x), the extra bits per symbol for coding data from p with a code built for q.
  • Gibbs' inequality: the theorem that KL divergence is never negative and is zero only for identical distributions.
  • Log loss: the cross-entropy loss of a classifier, −logq(the right answer) averaged over examples.
  • Maximum likelihood: choosing a model's parameters to make the observed data most probable; equivalent to minimising cross-entropy on that data.
  • Calibration: agreement between a model's stated probabilities and how often it's right.
  • Proper scoring rule: a way of scoring probabilistic predictions under which reporting your true probabilities is optimal.
  • Perplexity: 2cross-entropy, the effective number of equally likely choices a model faces per symbol.
  • Drift: a change over time in the distribution of the data a system receives.
  • Jensen–Shannon divergence: a symmetric, bounded divergence built from KL divergences to the average of two distributions.
  • Weight of evidence: logp(x)q(x), how much an observation favours p over q.
  • Stein's lemma: the result that the best error probability in testing p against q falls exponentially at rate D(p‖q).
  • Rate–distortion function: the fewest bits per symbol needed to describe a source within a given average distortion.