"Model B scored 2 points higher than model A" is the most common claim in AI work, and often it's noise: on another set of test items the order could flip. Lesson 98 put an error bar on one score. This lesson puts one on the difference between two. The trick is to compare the models item by item, on the same test: most items are ones both models get right, or both get wrong, and those say nothing about which is better. You'll build the range for a difference two ways, by formula and by resampling, learn what a p-value says and what it doesn't, and see why trying many variants almost guarantees a lucky win.
What you'll be able to do
Compare two models on the same test items by their paired differences: the mean, its standard error and a 95% range
Build the same range by resampling the items 2,000 times, and read it off a histogram with 0 marked
Say what a p-value is in one plain sentence, and what it isn't
Explain why trying many variants makes a lucky win likely, with 1 − 0.95ᵏ, and check a new model's lead in NumPy and PyTorch
Quick check
Have a guess before you start. On the same 200 test signs, model A reads 91% right and model B reads 93%. Is B the better model?
Can't tell yet: 2 points could be luck
Yes, because both saw the same signs
No: a 2-point gap never matters
Yes: 93% is more than 91%
Show the answer
Can't tell yet: 2 points could be luck
A gap between two scores wobbles, just as each score does. The AI part works this one out: on 200 signs the gap isn't proven, and on 2,000 signs the same gap is.
The math: differences, item by item
Purpose. Measure the gap between two models on the same test, and say how sure you can be of it.
Mark each model on each test item: 1 if it's right, 0 if it's wrong. Two models scored on the same items give paired results: one mark from each model for every item. Subtract item by item, B's mark minus A's, and you get each item's paired difference:
+1 where only B is right,
−1 where only A is right,
0 where they agree, both right or both wrong.
The mean of the differences is exactly B's accuracy minus A's. But now each item speaks for itself, and the items the models agree on add nothing.
Quick check
From lesson 98: values with standard deviation 0.6 are averaged over n = 100. What is the standard error of the average?
0.6
0.0036
0.06
0.006
Show the answer
0.06
σ ÷ √n = 0.6 ÷ √100 = 0.6 ÷ 10 = 0.06. The same rule gives the wobble of a mean difference.
The picture. Ten trail signs, marked for both models: A reads 7 right and B reads 9. Watch the differences two ways: as boxes of numbers, and as bars. An item's bar goes up to +1 if only B read it right, and down to −1 if only A did; the letters under each bar say who got that sign right. Then come the mean, its standard error, and, shaded, the range a true difference likely lies in. Keep an eye on the 0 line.
Try it now
Then change the fourth number in model A's marks to 0 and press Use these numbers. Now B never loses a sign, and the range only just clears 0.
Symbols and formula. For n paired items with differences d₁ to dₙ:
dˉ=n1i∑diSE=nsddˉ±1.96⋅SE
In plain words: the mean difference; its wobble, the differences' standard deviation over √n, as in lesson 98; and the range that covers the true difference about 95% of the time.
Does the range include 0? If it does, the test can't tell the models apart: "no difference at all" still fits what you saw. Here the range runs from −0.1719 to 0.5719, so 10 signs settle nothing. That isn't the same as "the models are equal": the true gap could be anywhere in that range, from A slightly ahead to B far ahead.
Quick check
Two models are compared on the same items. The 95% range for B − A runs from 0.004 to 0.036. What can you say?
A is better, by up to 3.6 points
B is better by exactly 2 points
B is better, though maybe by only 0.4 points
Nothing: the range is too narrow to read
Show the answer
B is better, though maybe by only 0.4 points
The whole range is above 0, so B really is ahead. How far is less sure: anywhere from 0.004 (0.4 points) to 0.036 (3.6 points).
What a p-value is. Many tools report a p-value: the chance of seeing a difference at least this big if the two models were really equally good. Under 0.05, by custom, the gap is called "significant": luck alone would rarely make one that big. A 95% range that leaves out 0 and a p-value under 0.05 almost always give the same verdict, two ways.
What it isn't. A p-value isn't the chance that the models are equal, and it isn't the chance that B is better. And a tiny p-value can come with a gap too small to matter: on a big enough test, a 0.1-point lead is "significant".
Many tries. When there is no real difference, each comparison still has a 5% chance of a false win. Try k variants, such as 20 prompts or 20 random seeds, keep the best, and the chance that at least one wins by luck alone is
P(at least one false win)=1−0.95k
For k = 20 that's 1 − 0.95²⁰ = 0.642: a lucky win is more likely than not. See it happen below.
In your own words
In your own words: why does comparing two models item by item on the same test tell you more than comparing their two scores?
Write a sentence or two, then compare it with a good answer in the lesson.
In Python: resample the differences
Purpose. Build the range by resampling, with no formula, then draw it.
The formula leans on the central limit theorem's bell, which is shaky with only 10 items. The bootstrap from lesson 98 needs no bell: draw 10 items from the 10 differences, with replacement, take their mean, and repeat 2,000 times. The middle 95% of those means, from the 2.5th to the 97.5th percentile, is the range.
import numpy as np
a = np.array([1, 0, 1, 1, 0, 1, 1, 0, 1, 1])
b = np.array([1, 1, 1, 0, 1, 1, 1, 1, 1, 1])
d = b - a
rng = np.random.default_rng(0)
boot = rng.choice(d, size=(2000, len(d))).mean(axis=1)
print(d.mean(), np.percentile(boot, [2.5, 97.5]))
Each of the 2,000 rows is one resample of the 10 signs. np.percentile takes a list of percentiles and returns both ends at once: −0.2 to 0.6, close to the formula's −0.1719 to 0.5719, and 0 is inside again.
Code flow. Here is the resampling, three resamples instead of 2,000. Step through it and watch each pick: some signs come up twice, some not at all, and that's what makes each resample's mean different.
The picture of 2,000 resamples. A histogram shows where the resampled means land, with a line at 0, no difference. plt.hist sorts values into bins and draws a bar for each; plt.axvline draws a vertical line.
Read the plot. Why does the range from the resamples include 0?
Every resample lands right of the 0 line
The resamples average exactly 0
The tallest bar sits right on the 0 line
Some resamples land on or left of the 0 line
Show the answer
Some resamples land on or left of the 0 line
A fair share of the bars sit at 0 or below: resamples where A did as well as B, or better. With that much of the histogram there, 0 lands inside the middle 95%.
A named mistake: two error bars instead of one. It's tempting to put an error bar on each model's score and call the gap real only if the two bars don't overlap. When the models were tested on the same items, that throws the pairing away: each bar carries the wobble of which items were picked, though both models met the same ones.
Worked example
Worked example: two overlapping bars, one real difference
Two sign readers on the same 400 practice signs. Put an error bar on each score, then one on the paired difference.
import numpy as np
a = np.ones(400)
b = np.ones(400)
b[0:4] = 0# 4 signs only A reads right
a[4:28] = 0# 24 signs only B reads right
a[28:84] = 0
b[28:84] = 0# 56 signs both get wrongfor p in [a.mean(), b.mean()]:
se = (p * (1 - p) / 400) ** 0.5print(p, round(p - 1.96 * se, 3), round(p + 1.96 * se, 3))
d = b - a
se = d.std() / 400 ** 0.5print(d.mean(), round(d.mean() - 1.96 * se, 3), round(d.mean() + 1.96 * se, 3))
In the lesson you can change this and run it.
A scores 0.8, with a bar from 0.761 to 0.839; B scores 0.85, with a bar from 0.815 to 0.885. The bars overlap, so the two-bar reading says "can't tell". The paired range says otherwise: 0.025 to 0.075, well clear of 0. B won 24 signs and lost 4, and the 372 signs they agreed on were never evidence either way. Pairing keeps exactly that.
Quick check
What does this print?
import numpy as np
a = np.array([1, 1, 0, 1, 0])
b = np.array([1, 0, 1, 1, 1])
d = b - a
print(d.tolist(), d.mean())
[0, -1, 1, 0, 1] 0.6
[0, 1, -1, 0, -1] -0.2
[0, -1, 1, 0, 1] 0.2
[1, 1, 1, 1, 1] 1.0
Show the answer
[0, -1, 1, 0, 1] 0.2
b − a item by item: 0, −1, +1, 0, +1. They add to 1, and 1 ÷ 5 = 0.2: B's 0.8 minus A's 0.6.
Drill
A paired range
Fix paired_range(a, b) so it returns the mean of the differences B − A and the ends of its 95% range, each rounded to 4 places. There are two slips. Then set can_tell to whether the range for the 10 signs leaves 0 out.
import numpy as np
defpaired_range(a, b):
d = a - b
mean = d.mean()
se = d.std() / len(d)
return (round(float(mean), 4), round(float(mean - 1.96 * se), 4), round(float(mean + 1.96 * se), 4))
a = np.array([1, 0, 1, 1, 0, 1, 1, 0, 1, 1])
b = np.array([1, 1, 1, 0, 1, 1, 1, 1, 1, 1])
mean, lo, hi = paired_range(a, b)
can_tell = Trueprint(mean, lo, hi, can_tell)
In the lesson, your code is checked as you write it.
In your own words
When you resample for a paired comparison, why must you draw whole items, both marks together, instead of A's marks and B's marks separately?
Write a sentence or two, then compare it with a good answer in the lesson.
In AI and ML: is the new sign reader better?
Purpose. Decide whether a new model's higher score on held-back data is real before you ship it.
The trail club's sign reader, A, and a new one, B, are both scored on the same 200 held-back signs: signs neither model trained on. A reads 91% right, B 93%. Mark them sign by sign, then put a range on the difference. np.tile(d, 10) repeats the 200 differences ten times: the same mix of wins and losses, as if the test had 2,000 signs.
import numpy as np
a = np.ones(200)
b = np.ones(200)
b[0:6] = 0# 6 signs only A reads right
a[6:16] = 0# 10 signs only B reads right
a[16:24] = 0
b[16:24] = 0# 8 signs both get wrong
d = b - a
print(a.mean(), b.mean(), int((d != 0).sum()))
for signs in [d, np.tile(d, 10)]:
se = signs.std() / len(signs) ** 0.5print(len(signs), round(signs.mean(), 3), round(signs.mean() - 1.96 * se, 4), round(signs.mean() + 1.96 * se, 4))
Only 16 of the 200 signs split the readers: B wins 10 of them and A wins 6. On 200 signs the range runs from −0.0191 to 0.0591: it includes 0, so B's 2-point lead isn't proven. On 2,000 signs the same lead gives a range from 0.0076 to 0.0324, clear of 0: real. Ten times the signs shrink the standard error by √10, about 3.2 times.
Quick check
On the 200 signs, B leads by 2 points but the range includes 0. What would settle it best?
Report the scores with more decimal places
Score both readers on many more held-back signs
Score B alone on a new set of signs
Score both again on the same 200 signs
Show the answer
Score both readers on many more held-back signs
More paired items shrink the standard error by √n. The same 2-point lead on 2,000 signs was clear of 0.
Many variants. Teams rarely compare just two models. They try 20 prompts, 20 learning rates or 20 random seeds, then keep the best. If none is truly better, each still has a 5% chance of a false win, and this cell counts the chance of at least one, for k tries. Its last number applies a fix called the Bonferroni rule: each try must reach p under 0.05 ÷ k instead of 0.05.
for k in [1, 5, 20]:
print(k, round(1 - 0.95 ** k, 3), round(1 - (1 - 0.05 / k) ** k, 3))
At 20 tries a lucky win comes up 64.2% of the time; with the stricter bar, 4.9%. The other habit that works: once a variant wins, test it again on fresh held-back items it has never been chosen on.
In PyTorch. The same resampling with tensors. torch.randint(0, n, (2000, n)) draws 2,000 rows of n sign positions, with replacement, and d[idx] reads those signs' differences. .float() turns the whole-number differences into decimals, because PyTorch won't average whole numbers, and .mean(dim=1) averages each row. torch.quantile reads both ends of the range. PyTorch's random numbers aren't NumPy's, so the ends differ in the last digit; the cell prints the spread and whether 0 is inside.
import torch
d = torch.zeros(200, dtype=torch.int64)
d[6:16] = 1# signs only B reads right
d[0:6] = -1# signs only A reads right
torch.manual_seed(0)
for signs in [d, d.repeat(10)]:
idx = torch.randint(0, len(signs), (2000, len(signs)))
boot = signs[idx].float().mean(dim=1)
lo, hi = torch.quantile(boot, torch.tensor([0.025, 0.975]))
print(len(signs), boot.shape, round(boot.std().item(), 2), lo.item() <= 0 <= hi.item())
The same verdicts as NumPy: 0 is inside the range for 200 signs and outside it for 2,000. The resamples' spreads, 0.02 and 0.01, are the standard errors the NumPy cell found, 0.0199 and 0.0063, to two places.
Quick check
What does this print?
import torch
d = torch.tensor([1, 0, -1, 1])
print(d.float().mean().item(), d.shape)
0.25 torch.Size([1])
0.25 torch.Size([4])
1 torch.Size([4])
0.75 torch.Size([4])
Show the answer
0.25 torch.Size([4])
The differences add to 1, and 1 ÷ 4 = 0.25. .float() makes them decimals so mean() can work, and the shape is 4 differences.
Drill
Resample, then decide
Write boot_range(d, seed): resample the differences 2,000 times with np.random.default_rng(seed), and return the 2.5th and 97.5th percentiles of the means, each rounded to 4 places. Then set real_200 and real_2000 to whether 0 is outside the range for the 200 signs and for the 2,000 signs (seed 0).
import numpy as np
a = np.ones(200)
b = np.ones(200)
b[0:6] = 0
a[6:16] = 0
a[16:24] = 0
b[16:24] = 0
d = b - a
defboot_range(d, seed):
rng = np.random.default_rng(seed)
boot = rng.choice(d, size=(2000, len(d))).mean(axis=1)
lo, hi = np.percentile(boot, [5, 95])
return (round(float(lo), 4), round(float(hi), 4))
real_200 = False
real_2000 = Falseprint(boot_range(d, 0), real_200, real_2000)
In the lesson, your code is checked as you write it.
In your own words
Your team tried 20 prompt variants, and one beat the current prompt with p = 0.03. What would you do before shipping it?
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