Nearly every classifier and every language model is trained on the same number: cross-entropy. Lesson 100 met it as a negative log-likelihood and lesson 102 as the log loss, without asking what it measures. This lesson gives it a meaning. An unlikely event is surprising, and surprise can be measured in bits: a coin toss carries one bit, a 1-in-8 event three. The average surprise of a source is its entropy, how unpredictable it is at best. The average surprise of the truth under a model's predictions is the cross-entropy, and it can never be less than the entropy: the gap is exactly what the model gets wrong. So a falling training loss means a model is being surprised less by real text. Perplexity, the number language models are compared by, is the same quantity read as "how many equally likely choices the model is torn between".
What you'll be able to do
Measure surprise as −log₂ p: rare events surprise more, and a 1-in-2 event is one bit
Compute entropy, the average surprise of a distribution, and cross-entropy, the average surprise of the truth under a model
Compute both as dot products with a log, and see that with one right answer cross-entropy is −log of its probability
Recognize cross-entropy as a language model's training loss, report it as perplexity, and check its value and its slope p − y with PyTorch's F.cross_entropy
Quick check
Have a guess before you start. Which surprises you more: a fair coin landing heads, or a fair die landing on 6?
Heads
They surprise you the same
The 6: it was less likely
Neither: both are possible
Show the answer
The 6: it was less likely
A 6 had chance 1/6, heads 1/2. The less likely an outcome, the more it surprises, and this lesson puts a number on that.
The math: surprise, averaged
Purpose. Measure how wrong a predicted distribution is, in one number.
Surprise. An event with chance p carries a surprise of −log₂ p, also written log₂(1/p), measured in bits. A 1-in-2 event is 1 bit, 1-in-4 is 2 bits, 1-in-8 is 3: each halving of the chance adds one bit. A certain event, p = 1, is 0 bits: no surprise. An event with p = 0.9 is 0.152 bits; one with p = 0.01 is 6.6 bits. The log makes surprises of independent events add, just as their chances multiply (lesson 89).
Entropy. The entropy of a distribution is its average surprise, each outcome's surprise weighted by its chance: H(p) = Σ pᵢ × (−log₂ pᵢ). A fair coin: ½ × 1 + ½ × 1 = 1 bit. A coin with chances 0.3 and 0.7: 0.88 bits, less, since it's more predictable. A two-headed coin: 0 bits. A fair die: log₂ 6 = 2.585 bits. Entropy is the smallest average surprise anyone can have about that source.
Quick check
From lesson 25: what is log₂ 8?
4
2.08
16
3
Show the answer
3
2³ = 8, so log₂ 8 = 3: a 1-in-8 event carries 3 bits of surprise.
Cross-entropy. Now a model predicts chances q while the truth follows p. The cross-entropy H(p, q) is the average surprise the model feels at what really happens: each outcome's surprise is measured with the model's q, but weighted by how often it truly happens, p. Step through it for a source with chances 0.5, 0.25 and 0.25 and a model that guesses 0.25, 0.25 and 0.5. The picture starts with the two side by side, each outcome's p beside its q. Then it draws each outcome's surprise as a bar, and last it weights the bars by p.
Try it now
Then set the model's chances to the truth's, 0.5, 0.25, 0.25, and press Use these numbers: the average drops to 1.5 bits, the entropy, the lowest possible.
In plain words: entropy is the truth's own average surprise; cross-entropy is the average surprise when using the model's chances; the difference, KL divergence, is never negative and is 0 only when the model's chances match the truth.
So a model can push its cross-entropy down toward the entropy, never below. Training drives it as low as it can, and whatever gap remains is the model's error; lesson 106 takes that gap apart. One right answer. For a training example the "truth" is one-hot: probability 1 on the right answer, 0 elsewhere. Then every term but one vanishes, and H(p, q) = −log₂ q of the right answer, exactly lesson 100's negative log-likelihood for one observation.
Quick check
What is the entropy of a fair coin?
0 bits
2 bits
1 bit
0.5 bits
Show the answer
1 bit
Each side has chance ½ and surprise 1 bit, so the average is 1 bit: the unit itself.
In your own words
In your own words: why can a model's cross-entropy never be lower than the truth's entropy?
Write a sentence or two, then compare it with a good answer in the lesson.
In Python: dot products with a log
Purpose. Compute entropy and cross-entropy in one line each, and check the one-hot case.
import numpy as np
p = np.array([0.5, 0.25, 0.25])
q = np.array([0.25, 0.25, 0.5])
H = p @ np.log2(1 / p)
CE = p @ np.log2(1 / q)
print(H, CE, CE - H)
y = np.array([0.0, 1.0, 0.0])
guess = np.array([0.2, 0.7, 0.1])
print(round(float(y @ np.log2(1 / guess)), 4), round(float(np.log2(1 / 0.7)), 4))
It runs right here in your browser, with nothing to install.
Each is a dot product (lesson 50): the chances p dotted with the surprises. With a one-hot y, the dot product picks out a single surprise, the right answer's, 0.5146 bits. Libraries use the natural log instead of log₂; the answer is then in nats (1 nat = 1.443 bits), and everything else stays the same.
Code flow. Step through the same lines one at a time. Watch the boxes of s: the model's surprise at each outcome, the flow's −log₂ q cells. Each total is then one dot product with a row of surprises.
A named mistake: 0 × log 0. An outcome with p = 0 should add nothing to the entropy, since it never happens. But np.log2(0) is minus infinity, and 0 × infinity is nan, so a plain formula turns the whole sum into nan. Either skip the zero chances, p[p > 0], or follow the convention that 0 × log 0 = 0. That's safe for zeros in p, the truth's chances; a zero in the model's q is another story.
Worked example
Worked example: the entropies of three distributions
Compute the entropy of a fair coin, a 0.3/0.7 coin and a fair die, skipping zero chances safely.
The fair coin carries 1 bit, the lopsided coin 0.8813, the fair die 2.585, which is log₂ 6, and the certain coin 0. More outcomes and more even chances mean more entropy; a source that always does the same thing has none. The p[p > 0] mask drops the zero chance before taking logs, so the certain coin gives 0 instead of nan.
Four right-answer chances give surprises 0.32, 1, 2 and 0.15 bits, averaging 0.8685; 2 to that power, the perplexity, is 1.826.
Drill
Entropy and cross-entropy
Write entropy(p) (skipping zero chances) and cross_entropy(p, q), both in bits. Then set h, ce and kl for p = (0.5, 0.25, 0.25) and q = (0.25, 0.25, 0.5).
import numpy as np
defentropy(p):
return0.0defcross_entropy(p, q):
return0.0
p = np.array([0.5, 0.25, 0.25])
q = np.array([0.25, 0.25, 0.5])
h = entropy(p)
ce = cross_entropy(p, q)
kl = 0.0print(h, ce, kl)
In the lesson, your code is checked as you write it.
In your own words
Why does skipping p = 0 in the entropy make sense, while a model's q = 0 for a real outcome can't be skipped?
Write a sentence or two, then compare it with a good answer in the lesson.
In AI and ML: the loss a language model is trained on
Purpose. Read a training loss as average surprise, and see its slope.
The loss. A language model's loss on a text is its average cross-entropy per word: for each word, −log of the probability it gave the word that actually came next, averaged. The camp-log model of lesson 88, shown a new sentence, "the tent was warm", gives the three words chances 0.2, 1 and 1/3. The cell finds each word's surprise, their average and 2 to that power:
import numpy as np
right = np.array([0.2, 1.0, 1 / 3])
bits = np.log2(1 / right)
loss = bits.mean()
print(bits.round(2).tolist(), round(float(loss), 2), round(float(2 ** loss), 2))
Surprises of 2.32, 0 and 1.58 bits average 1.3 bits per word. Perplexity is 2 to that power, 2.47: on average the model is as unsure as if choosing between about two and a half equally likely words. A better model has lower perplexity on new text. With the natural log, as libraries use, perplexity is e to the loss instead; it's the same number, as PyTorch shows below.
Quick check
A language model's perplexity on a test text drops from 40 to 20 after more training. What does that mean?
It now gets twice as many next words exactly right
The text got easier
Its loss doubled
It's half as unsure: like 20 equal choices instead of 40
Show the answer
It's half as unsure: like 20 equal choices instead of 40
Perplexity reads the average surprise as an effective number of choices; halving it means a full bit less surprise per word.
The slope. Softmax (lesson 104) followed by cross-entropy has the simplest possible slope with respect to the scores: p − y, the predicted chances minus the one-hot truth, the same result as lesson 102's single neuron. For scores 2, 1 and 0.1 with "tent", the second class, correct, the chances are 0.659, 0.242 and 0.099, and the slope is (0.659, −0.758, 0.099): push the right class's score up, and the others down in proportion to how much chance they stole. That one line is where backpropagation starts in every language model.
In PyTorch.F.cross_entropy(logits, target) takes the raw scores, not the chances, and does the softmax and the −log of the right answer's chance in one call, in nats, averaged over the batch. Made with requires_grad=True, as in lesson 82, the scores get their slope from backward():
import math
import torch
import torch.nn.functional as F
right = torch.tensor([0.2, 1.0, 1 / 3])
nats = -torch.log(right).mean()
print(round(nats.item(), 4), round(torch.exp(nats).item(), 2))
logits = torch.tensor([[2.0, 1.0, 0.1]], requires_grad=True)
loss = F.cross_entropy(logits, torch.tensor([1]))
loss.backward()
hand = -math.log(math.exp(1) / (math.exp(2) + math.exp(1) + math.exp(0.1)))
print(round(loss.item(), 4), round(hand, 4))
print(logits.grad)
The camp-log sentence costs 0.9027 nats per word, and torch.exp of that is 2.47, the perplexity the NumPy cell found from bits. F.cross_entropy agrees with the hand recipe, softmax and then −ln of tent's chance: 1.417 nats both ways. And logits.grad is p − y, the slope above to 3 places: 0.659, −0.7576 and 0.0986.
Quick check
What does this print?
import numpy as np
h = np.array([1.0, 2.0, 3.0])
print((2 ** h).tolist())
[0.5, 0.25, 0.125]
[2.0, 4.0, 8.0]
[2.0, 3.0, 4.0]
[1.0, 4.0, 9.0]
Show the answer
[2.0, 4.0, 8.0]
Perplexity is 2 to the cross-entropy in bits: each extra bit doubles the number of equally likely choices.
Drill
The loss before and after an improvement
before and after hold the chances an old and an improved model gave the right next words in the same five-word test. Set ce_before and ce_after to the average cross-entropy in bits, rounded to 3, ppl_after to 2 to the improved model's cross-entropy (unrounded), rounded to 3, and grad to the slope p − y for scores (2, 1, 0.1) with class 1 correct, rounded to 3, as a list.
import numpy as np
before = np.array([0.2, 1.0, 1 / 3, 0.6, 1 / 3])
after = np.array([0.4, 0.9, 0.5, 0.6, 0.5])
ce_before = 0
ce_after = 0
ppl_after = 0
z = np.array([2.0, 1.0, 0.1])
y = np.array([0.0, 1.0, 0.0])
grad = []
print(ce_before, ce_after, ppl_after, grad)
In the lesson, your code is checked as you write it.
In your own words
The slope p − y pushes down every wrong class's score in proportion to its chance. Why is that a sensible way to learn?
Write a sentence or two, then compare it with a good answer in the lesson.
31Formulas with fractions: clear them firstFreeClearing denominators, cross-multiplying, a letter in the bottom, and reciprocal formulas like 1/R = 1/R₁ + 1/R₂.35 min
37Inverse functions, lines and scalingFreeUndoing a function by making x the subject, domains that allow it, line forms, and unscaling predictions.40 min
38Sequences and sums: find n, a, d and rFreeEvery letter of the arithmetic and geometric formulas as the subject, and an average's window from its decay.40 min
40Review: rearrange anything (algebra)FreeBroken rearrangements to fix, mixed practice from the whole algebra block, a strategy chart, and its formula sheet.35 min
41Coordinates and distanceFreePoints as (x, y), Pythagoras, distance in any number of coordinates, and nearest neighbors.42 min
42Angles, degrees and radiansFreeMeasuring a turn, converting units, arcs, and the angle between two arrows.36 min
43Sine and cosineFreeAcross and up: right triangles, the unit circle, and directions and rotations.42 min
44Waves: height, speed and shiftFreeAmplitude, period and phase, sampling a wave, and position codes in transformers.37 min
68Vector equations: rearranging with arrowsFreeSolving for a vector or a scale, recovering a gradient from two weight snapshots, and an angle from a dot product.40 min
87Counting: choices, orders and groupsFreeThe counting principle, factorials, ordered picks and groups, and why attention's cost grows with the square of the length.43 min
88Probability: from counts to chancesFreeEqually likely outcomes, the complement, distributions, seeded simulation, and a next-word model.43 min
89Combining events: and, or, independentFreeThe or rule, independence, probability trees, drawing with and without replacement, and chains of steps.42 min
100Maximum likelihoodFreeLikelihoods as products, log-likelihoods as sums, grid search, underflow, and the negative log-likelihood loss.45 min
101Linear regression: the best lineFreeResiduals, least squares by formula, three roads to one line, the matrix form, and train versus test error.45 min
109One neuron, start to finishFreeWeighted sum, activation, loss, slopes and update, by hand and in code, and what one straight line can and can't split.45 min
111Training a small networkFreeThe backward pass in matrix form, gradient checks, a full training loop, and reading loss curves.45 min
112The same network in PyTorchFreenn.Sequential with the NumPy weights loaded, the same loss and slopes, then SGD and mini-batches.45 min
113Attention as matrix mathFreeScaled dot-product scores, the causal mask, a row-by-row softmax, and blending value vectors.45 min
114Residual connections and layer normFreeAdding the input back and why its slope keeps learning alive, layer norm by hand, and add and norm.40 min
115A transformer block, start to finishFreeA sentence through embeddings, attention, add and norm, a small network and next-word scores, every shape named.45 min
117Final test: transpose any formulaFreeSlips to fix from every topic, mixed practice of every kind of rearranging, the strategy chart and the full sheet.45 min
Learn the math behind AI from arithmetic up: numbers, algebra, vectors and matrices, calculus, probability and statistics, each shown as numbers moving and checked in Python, ending with a network you build and train from the formulas.
See the course →
Never trained an AI? Teach a small one to write, right in your browser. It takes about 20 seconds and needs no account. Teach it to write