Information Theory CompanionInformation Theory · Companion
0 / 0

Workbench / Information Theory Companion

B1·11

Information in Machine Learning: Cross-Entropy and KL Divergence

Around chapter 11: how cross-entropy, divergence, log loss and perplexity tie the whole book together; three other ways to see them; what the chapter simplifies (divergence estimated from samples depends on smoothing, perplexities of 2,572 and 4.38 can describe nearly the same model, and KL stops growing once two distributions stop overlapping); how scikit-learn's log loss clips probabilities and why a certain mistake costs it exactly 52 bits; four debugging drills; and interview questions.

6 topics · ~18 min read
Updated Suggest a correction

Understanding it better

Concept map

  • Surprise (chapter 1) averaged under the truth → entropy (chapter 4); under a model → cross-entropy.
  • Cross-entropy = entropy + KL divergence: the unavoidable cost plus the cost of the wrong model.
  • Code lengths (chapters 5 and 6) → an arithmetic coder given the wrong model pays exactly the cross-entropy.
  • Gibbs' inequality (the lnu≤u−1 of chapter 4) → KL ≥ 0 → every model is an upper bound (chapter 10).
  • Mutual information (chapter 7) = KL from independence; capacity (chapter 9) = the best average KL between outputs.
  • Maximum likelihood = minimum cross-entropy → log loss, a proper scoring rule → calibration.
  • Overfitting (chapter 7) → held-out cross-entropy and perplexity.
  • Bias of estimates (chapter 4) → the noise floor of measured KL → calibrated drift alarms.
  • Evidence: KL bits per observation (Stein, Sanov) → classification by surprise (chapter 10).
  • Rate–distortion: chapter 9's mirror image for lossy compression.

Explain it differently

A phrasebook for the wrong country. You pack a phrasebook built for French tourists and use it in England: it has short entries for words you rarely need and long ones for words you need all the time. You still get by, but every conversation takes longer. The extra length is the divergence; the conversation itself (what you need to say) is the entropy.

A forecaster's score. A weather forecaster who says "90 % rain" every day is judged by log loss: rewarded when it rains, punished hard on dry days. A forecaster who says "50 %" is never embarrassed and never impressive. The best score goes to the one whose 70 % days are rainy 70 % of the time: calibration, not boldness.

Weighing evidence. Each letter of a text is a small weight on a balance between "English" and "French". Most letters move it a little, a few move it a lot, and over a sentence the balance tips decisively. The average weight per letter is the divergence, and the time it takes to tip is set by it.

Gaps and misconceptions

What the chapter oversimplifies

1. "The divergence between English and French letters is 0.263 bits", from the full declarations, smoothed by half a count. From samples, the answer depends on the smoothing:

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

def letters(f):
    return re.sub(r"[^a-z]", "", Path("data/udhr", f).read_bytes().decode("latin-1").lower())
eng, fra = letters("English-Latin1"), letters("French_Francais-Latin1")
az = "abcdefghijklmnopqrstuvwxyz"
rng = random.Random(11)
print("D(English letters || French letters), estimated from samples of each")
print(f"{'sample':>8}" + "".join(f"{'smoothing ' + str(a):>16}" for a in (0, 0.01, 0.5, 1)))
for n in (100, 1_000, 8_000):
    row = []
    for a in (0, 0.01, 0.5, 1):
        vals = []
        for _ in range(50):
            se, sf = (rng.sample(eng, n), rng.sample(fra, n)) if n < 8_000 else (eng, fra)
            p, q = distribution(se, az, a), distribution(sf, az, a)
            vals.append(kl(p, q) if all(q[c] > 0 for c in az if p[c] > 0) else float("inf"))
        finite = [v for v in vals if v != float("inf")]
        row.append(f"{sum(finite) / len(finite):.3f} ({len(vals) - len(finite)} inf)" if finite else "all inf")
    print(f"{n:>8,}" + "".join(f"{r:>16}" for r in row))
Text
D(English letters || French letters), estimated from samples of each
  sample     smoothing 0  smoothing 0.01   smoothing 0.5     smoothing 1
     100         all inf   0.872 (0 inf)   0.371 (0 inf)   0.277 (0 inf)
   1,000         all inf   0.373 (0 inf)   0.255 (0 inf)   0.225 (0 inf)
   8,000         all inf   0.330 (0 inf)   0.263 (0 inf)   0.251 (0 inf)

With no smoothing, every estimate is infinite, even from the full texts: some letter of the English sample never appears in the French one, so the French "model" calls it impossible. With a tiny pseudo-count (0.01), samples of 100 letters give 0.872 bits, far too high, because rare letters get absurdly small probabilities; with 0.5 or 1, the estimates are lower and steadier, but they too depend on the choice (0.371 and 0.277 at 100 letters). Only with thousands of letters do they settle near 0.25 to 0.33. Divergences estimated from counts need a stated smoothing and enough data, and two figures computed with different choices aren't comparable.

2. "Perplexity measures a model's uncertainty", in units that depend on the tokens. A model that predicts whole words and one that predicts letters can describe the same text almost equally well and report wildly different perplexities:

Python
import math, re
from collections import Counter
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)
start = text.index(" ", cut) + 1                                 # whole words only, each followed by a space
test = text[start:text.rindex(" ", 0, start + 20_000) + 1]

words = Counter(text[:cut].split())
total, vocab = sum(words.values()), len(words) + 1             # +1: one shared slot for unseen words
spell = Blend(sorted(set(text)), 2); spell.train(text[:cut])   # unseen words are spelled out letter by letter
bits = 0.0
for w in test.split():
    if w in words:
        bits -= math.log2((words[w] + 0.5) / (total + 0.5 * vocab))
    else:
        bits -= math.log2(0.5 / (total + 0.5 * vocab))
        s = " " + w + " "
        bits -= sum(math.log2(spell.probs(s[max(0, j - 2):j])[s[j]]) for j in range(1, len(s)))
n_words, n_chars = len(test.split()), len(test)
print(f"word model (each word on its own): {bits / n_words:.2f} bits per word, perplexity {2 ** (bits / n_words):,.0f} per word, "
      f"{bits / n_chars:.3f} bits per character")
m = Blend(sorted(set(text)), 5); m.train(text[:cut])
cbits = -sum(math.log2(m.probs(text[start + i - 5:start + i])[test[i]]) for i in range(len(test)))
print(f"character model (5 letters of context): {cbits / n_chars:.3f} bits per character, perplexity {2 ** (cbits / n_chars):.2f} per character, "
      f"{cbits / n_words:.2f} bits per word")
print(f"{n_words:,} words, {n_chars:,} characters: {n_chars / n_words:.2f} characters per word")
Text
word model (each word on its own): 11.33 bits per word, perplexity 2,572 per word, 2.240 bits per character
character model (5 letters of context): 2.130 bits per character, perplexity 4.38 per character, 10.77 bits per word
3,954 words, 20,000 characters: 5.06 characters per word

The word model (each word predicted from its overall frequency, unseen words spelled out) has a perplexity of 2,572 per word; the character model, 4.38 per character. In bits per character, they're 2.240 and 2.130: close, with the character model slightly better. Perplexity per token depends on how long tokens are, and modern language models use sub-word tokens of varying length, so perplexities from different tokenisers can't be compared; bits per character (or per byte) of the same text can.

3. "KL measures how far data has drifted", but not how far in value. For a numerical feature, a small shift of a narrow peak and a huge one can look the same:

Python
import numpy as np
from scipy.stats import wasserstein_distance
from kl import kl

bins = np.arange(100)                                   # e.g. response time in 10 ms bins
def histogram(centre):
    w = np.exp(-0.5 * ((bins - centre) / 2.0) ** 2) + 1e-6   # a narrow peak, with a little probability everywhere
    return dict(zip(bins, w / w.sum()))
reference = histogram(20)
print(f"{'peak moved by':>14}{'KL (bits)':>11}{'Jensen-Shannon':>16}{'Wasserstein (bins)':>20}")
for shift in (1, 3, 10, 30, 60):
    now = histogram(20 + shift)
    m = {b: (reference[b] + now[b]) / 2 for b in bins}
    js = 0.5 * kl(now, m) + 0.5 * kl(reference, m)
    w = wasserstein_distance(bins, bins, list(now.values()), list(reference.values()))
    print(f"{shift:>14}{kl(now, reference):>11.3f}{js:>16.3f}{w:>20.2f}")
Text
 peak moved by  KL (bits)  Jensen-Shannon  Wasserstein (bins)
             1      0.180           0.044                1.00
             3      1.622           0.319                3.00
            10     15.477           0.975               10.00
            30     19.210           1.000               30.00
            60     19.210           1.000               60.00

As a narrow peak moves by 1, 3 and 10 bins, KL grows quickly (0.180, 1.622, 15.477 bits), but once the old and new peaks stop overlapping it stops at 19.21 bits whether the peak moved 30 bins or 60: only the smoothing floor sets it. Jensen–Shannon stops at its maximum, 1 bit. The Wasserstein distance, how far probability has to move, keeps growing in proportion to the shift (30 against 60 bins). KL and its relatives compare how much probability overlaps, not where it is; for numerical features where "how far" matters (latency, prices), a distance that knows the order of the values is a better alarm, or a companion to KL.

Common misconceptions

Misconception What's actually true Where it's shown
"KL between two samples is a well-defined number." Unsmoothed it was infinite; smoothed, it ranged from 0.277 to 0.872 at 100 letters. What the chapter oversimplifies, point 1
"A perplexity of 2,572 is far worse than 4.38." Per word against per character: 2.240 against 2.130 bits per character. What the chapter oversimplifies, point 2
"A larger KL always means a larger shift." Moving 30 bins or 60 gave the same 19.21 bits. What the chapter oversimplifies, point 3
"Log loss can be arbitrarily large in scikit-learn." It clips probabilities, so one certain mistake costs 36.04 nats, 52 bits. Code walkthrough
"If accuracy is fine, the probabilities are fine." The wrong column gave 96.5 % accuracy and 12.9 bits per case. Drill D1
"KL is KL, whichever way it's computed." Reversed, every normal window scored infinity. Drill D2
"Perplexity is 2 to the power of the loss." Only if the loss is in bits; in nats it's e to the loss. Drill D3
"A random split gives an honest test set." 741 of 3,278 test lines were also in the training lines. Drill D4

Theoretical gaps: the ideas behind the chapter

  • Information geometry. For nearby distributions, KL behaves like a squared distance whose ruler is the Fisher information, so families of distributions form curved spaces in which maximum likelihood and its uncertainty have geometric meanings (Shun-ichi Amari, from the 1980s). It's why natural-gradient methods rescale updates by the Fisher information.
  • Variational bounds. Many quantities that can't be computed (the probability of the data under a model with hidden variables, mutual information between high-dimensional variables) are bounded using KL's non-negativity: the evidence lower bound (ELBO) of variational autoencoders and the contrastive bounds used in representation learning are both Gibbs' inequality in disguise.
  • Compression is prediction. Because cross-entropy is code length, any predictor is a compressor and any compressor a predictor. This equivalence underlies the minimum description length principle, the Hutter Prize for compressing Wikipedia, and the use of compression to evaluate language models.

Applying it

Code walkthrough

scikit-learn's log_loss computes the average cross-entropy of probabilistic predictions. After validating its inputs, it calls this function, from sklearn/metrics/_classification.py in scikit-learn 1.9 (on your computer: python3 -c "import sklearn.metrics._classification as m; print(m.__file__)"):

Python
def _log_loss(transformed_labels, y_proba, *, normalize=True, sample_weight=None):
    """Log loss for transformed labels and validated probabilistic predictions."""
    xp, _, device_ = get_namespace_and_device(y_proba)
    if sample_weight is not None:
        sample_weight = move_to(sample_weight, xp=xp, device=device_)
    eps = xp.finfo(y_proba.dtype).eps
    y_proba = xp.clip(y_proba, eps, 1 - eps)
    transformed_labels = xp.astype(transformed_labels, y_proba.dtype, copy=False)
    loss = -xp.sum(_xlogy(transformed_labels, y_proba, xp=xp), axis=1)
    return float(_average(loss, weights=sample_weight, normalize=normalize))

transformed_labels is one row per example with a 1 in the column of the true class (one-hot), so -sum(xlogy(labels, proba)) picks out −lnq(true class) for each row: the chapter's surprise, in nats. xlogy treats 0×ln0 as 0. The clip to [ϵ,1−ϵ], with ϵ the machine epsilon (about 2.2×10−16), keeps a probability of exactly 0 from producing an infinite loss. Before this, the validation step checks that each row's probabilities add up to 1, and only warns if they don't. Measured:

Python
import math, warnings
import numpy as np
from sklearn.metrics import log_loss

y = [1, 0, 1, 1]
p = [0.8, 0.4, 0.95, 0.3]                                    # each case's probability of class 1
nats = log_loss(y, p)
print(f"log_loss: {nats:.4f} nats = {nats / math.log(2):.4f} bits per case")
print(f"a certain mistake (p = 0 for what happened): {log_loss([1], [0.0], labels=[0, 1]):.2f} nats, "
      f"= -ln(machine epsilon) = {-math.log(np.finfo(float).eps):.2f} nats = {-math.log2(np.finfo(float).eps):.0f} bits")
with warnings.catch_warnings(record=True) as caught:
    warnings.simplefilter("always")
    value = log_loss([0, 1], [[0.5, 0.2], [0.5, 0.2]])           # each row adds to 0.7, not 1
print(f"probabilities that don't add to 1: {value:.4f} nats, with the warning: {caught[0].message}")
Text
log_loss: 0.4973 nats = 0.7175 bits per case
a certain mistake (p = 0 for what happened): 36.04 nats, = -ln(machine epsilon) = 36.04 nats = 52 bits
probabilities that don't add to 1: 1.1513 nats, with the warning: The y_prob values do not sum to one. Make sure to pass probabilities.

The four predictions score 0.4973 nats, the exercises' P1 answer of 0.7175 bits. A prediction that gave the true class probability 0 costs 36.04 nats, exactly −lnϵ, 52 bits, instead of infinity. Probabilities that add to 0.7 are accepted with a warning and give a number (1.1513 nats) that isn't a cross-entropy of anything.

Read it yourself

Using the code above: why clip at ϵ rather than let the loss be infinite? What does the clipping hide, and why does the function only warn, rather than fail, when rows don't add to 1?

Debugging drills

D1. Accurate, with a terrible log loss

A model reports 96.5 % accuracy and a log loss of 12.9 bits per case, worse than guessing.

Python
import numpy as np
from sklearn.datasets import load_breast_cancer
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import log_loss, accuracy_score
from sklearn.model_selection import train_test_split
from sklearn.pipeline import make_pipeline
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)
model = make_pipeline(StandardScaler(), LogisticRegression(max_iter=5000)).fit(Xtr, ytr)
p_class1 = model.predict_proba(Xte)[:, 0]                 # probability of class 1, for the report
print(f"accuracy {accuracy_score(yte, model.predict(Xte)):.3f}, log loss {log_loss(yte, p_class1) / np.log(2):.3f} bits per case")
print("classes_ =", model.classes_)
Text
accuracy 0.965, log loss 12.853 bits per case
classes_ = [0 1]

D2. Every normal window raises an alarm

A drift monitor flags all 20 windows of perfectly normal text, each with an infinite score.

Python
import math, random, 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())
reference = distribution(plays[:200_000], az)
rng = random.Random(11)
alerts = 0
for w in range(20):                                         # twenty normal windows of 300 letters
    start = 200_000 + 300 * w
    window = distribution(plays[start:start + 300], az)
    score = kl(reference, window) if all(window[c] > 0 for c in az if reference[c] > 0) else math.inf
    alerts += score > 0.1
    if w < 5:
        print(f"window {w + 1}: score {score}")
print(f"alerts in 20 normal windows: {alerts}")
Text
window 1: score inf
window 2: score inf
window 3: score inf
window 4: score inf
window 5: score inf
alerts in 20 normal windows: 20

D3. A perplexity that's too good to be true

A team reports a character perplexity of 2.78 for the chapter's five-letter model, where the chapter measured 4.38 on the same text.

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)
m = Blend(sorted(set(text)), 5); m.train(text[:cut])
test = text[cut:cut + 20_000]
loss = -sum(math.log(m.probs(text[cut + i - 5:cut + i])[test[i]]) for i in range(len(test))) / len(test)   # mean loss, as frameworks report it
print(f"mean loss {loss:.4f}; reported perplexity 2 ** loss = {2 ** loss:.2f}")
Text
mean loss 1.4766; reported perplexity 2 ** loss = 2.78

D4. A held-out score that's better than the chapter's

A random 90/10 split of the plays' lines gives a held-out cross-entropy of 1.967 bits per symbol for the five-letter model, better than the chapter's 2.130.

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

norm = lambda s: re.sub(r"[^a-z]+", " ", s.lower())
lines = [norm(l) for l in Path("data/shakespeare.txt").read_text().split("\n") if l.strip()]
random.Random(11).shuffle(lines)                     # split lines at random: 90 % to train, 10 % to test
cut = int(len(lines) * 0.9)
train, test = " ".join(lines[:cut]), " ".join(lines[cut:])[:20_000]
alphabet = sorted(set(train + test))
m = Blend(alphabet, 5); m.train(train)
bits = -sum(math.log2(m.probs(test[max(0, i - 5):i])[test[i]]) for i in range(len(test))) / len(test)
print(f"held-out cross-entropy {bits:.3f} bits per symbol, perplexity {2 ** bits:.2f}")
print(f"test lines that also appear in the training lines: {sum(l in set(lines[:cut]) for l in lines[cut:])} of {len(lines) - cut}")
Text
held-out cross-entropy 1.967 bits per symbol, perplexity 3.91
test lines that also appear in the training lines: 741 of 3278

Career-oriented

Interview prep

Mid level

Q1. What's the relationship between cross-entropy, entropy and KL divergence?

How to get there. H(p,q)=H(p)+D(p‖q).

Q2. Why is log loss preferred to accuracy for training classifiers, and when would you still report accuracy?

How to get there. Proper scoring, gradients, calibration.

Senior level

Q3. How would you detect that the data a production model receives has changed?

How to get there. Divergence with calibration, the companion's point 3, outputs and quality.

Q4. A model's validation perplexity is much better than expected. How do you check it?

How to get there. Units, leakage, normalisation.

Staff level

Q5. Leadership wants a single "model quality" number on the company dashboard for a fraud-detection model. What do you propose?

How to get there. Calibration, costs, and what one number hides.

Q6. Your team proposes replacing a well-tuned gradient-boosted classifier with a large neural network because its log loss is 5 % lower on the validation set. How do you decide?

How to get there. What 5 % lower log loss means, robustness, cost.