Index Ai Academy
Foundation · Statistics and information

Is the difference real? Comparing two models

Paired differences, a bootstrap interval, what a p-value is and isn't, and why many tries make lucky wins.

About 40 minutes · Free lesson

What it covers6

Why it matters

"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?
  1. Can't tell yet: 2 points could be luck
  2. Yes, because both saw the same signs
  3. No: a 2-point gap never matters
  4. 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?
  1. 0.6
  2. 0.0036
  3. 0.06
  4. 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ˉ=1n∑idiSE=sdndˉ±1.96⋅SE\bar{d} = \frac{1}{n}\sum_i d_i \qquad \text{SE} = \frac{s_d}{\sqrt{n}} \qquad \bar{d} \pm 1.96 \cdot \text{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?
  1. A is better, by up to 3.6 points
  2. B is better by exactly 2 points
  3. B is better, though maybe by only 0.4 points
  4. 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.95kP(\text{at least one false win}) = 1 - 0.95^{k}

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.

import numpy as np
import matplotlib.pyplot as plt
d = np.array([0, 1, 0, -1, 1, 0, 0, 1, 0, 0])
rng = np.random.default_rng(0)
boot = rng.choice(d, size=(2000, 10)).mean(axis=1)
plt.hist(boot, bins=np.arange(-0.45, 0.8, 0.1))
plt.axvline(0, color="black")
plt.xlabel("mean difference, B - A")
plt.ylabel("resamples")
plt.show()
Quick check
Read the plot. Why does the range from the resamples include 0?
  1. Every resample lands right of the 0 line
  2. The resamples average exactly 0
  3. The tallest bar sits right on the 0 line
  4. 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 wrong
for p in [a.mean(), b.mean()]:
    se = (p * (1 - p) / 400) ** 0.5
    print(p, round(p - 1.96 * se, 3), round(p + 1.96 * se, 3))
d = b - a
se = d.std() / 400 ** 0.5
print(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())
  1. [0, -1, 1, 0, 1] 0.6
  2. [0, 1, -1, 0, -1] -0.2
  3. [0, -1, 1, 0, 1] 0.2
  4. [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

def paired_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 = True
print(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.5
    print(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?
  1. Report the scores with more decimal places
  2. Score both readers on many more held-back signs
  3. Score B alone on a new set of signs
  4. 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)
  1. 0.25 torch.Size([1])
  2. 0.25 torch.Size([4])
  3. 1 torch.Size([4])
  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

def boot_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 = False
print(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.

Goes deeper in

Practice what you just read

  • 6 code examples you can edit and run
  • a practice exercise that checks your code
  • a 5-question quiz
  • 9 review cards for spaced repetition

Try a quiz question

A comparison reports p = 0.03. What does that mean?

  1. With equal models, a gap this big turns up only 3% of the time
  2. There is a 3% chance that the two models are equally good
  3. There is a 97% chance that model B is the better one
  4. Model B is 3% more accurate than model A

Answer it at the end of the lesson to see if you're right, and why.

Before this lesson

Keep learning

Where this lesson leads.

575 lessons in thirteen phases. 176 are free without an account, and a free account opens the rest. See every lesson.

Foundation · about 96 hours of study

Foundation math

From whole numbers to the math inside a neural network: each idea by hand, in Python, and in AI 118 lessons All free
  1. Numbers and place value FreeWhat a digit's place is worth, the number line, and Python as a calculator that never tires.36 min
  2. Multiplying and dividing: groups FreeEqual groups, quotient and remainder, and cutting training data into batches.35 min
  3. Order of operations, and names for numbers FreeBrackets, powers, then multiply and divide, then add and subtract; variables hold numbers.36 min
  4. Numbers below zero FreeThe number line through zero, sign rules, distance from zero, and an error's direction and size.37 min
  5. Fractions: equal parts, equal fractions, adding FreePieces of a whole, equal fractions, and re-cutting to add; accuracy as a fraction.45 min
  6. Multiplying and dividing fractions FreeA share of a share, dividing by flipping, and why chances in a row get small.35 min
  7. Decimals and rounding FreeFractions in place value, rounding, and why 0.1 + 0.2 isn't exactly 0.3.36 min
  8. Percentages FreePer hundred, percent change, percentage points, and the accuracy and error rates of models.35 min
  9. Ratios, rates and proportion FreeSharing in a ratio, rates per unit, scaling, and splitting data 80/10/10.35 min
  10. Powers and roots FreeRepeated multiplying, the laws of exponents, square roots, and squared error.43 min
  11. Very big and very small numbers FreePowers of ten, e-notation like 3e-4, orders of magnitude, and a model's size in memory.36 min
  12. Bits, bytes and floats: how numbers are stored FreeBase 2, what n bits can hold, a float as sign, power and digits, and a tensor's memory.35 min
  13. Review: find the slip (numbers) FreeBroken calculations to fix, mixed practice from the whole module, and its formula sheet.34 min
  14. Letters for numbers FreeVariables, terms and like terms, substitution, and a model's formula as a Python function.41 min
  15. Expanding and factoring FreeBrackets as areas, pulling out common factors, and a squared error expanded into a bowl.41 min
  16. Solving equations: keep the balance FreeThe same move on both sides, undoing steps in reverse, and running a model's formula backward.41 min
  17. Rearranging a formula FreeMaking any letter the subject, round-trip checks, and planning a training run.36 min
  18. Inequalities and true-or-false FreeRanges, flipping the sign, if and elif, and the thresholds, clips and ReLU inside a model.42 min
  19. Functions: a rule from input to output Freef(x) notation, tables and graphs, domain and range, loops over lists, and loss as a function.42 min
  20. Chaining and undoing functions Freeg(f(x)), inverses that undo, scaling and unscaling, and a network as a chain.42 min
  21. Straight lines: slope and intercept FreeRise over run, the line through two points, and a model's weight and bias as slope and intercept.42 min
  22. Two equations, two unknowns FreeSubstitution and elimination, where lines cross, and why models are fitted, not solved.42 min
  23. Quadratics: bowls and their lowest point FreeRoots by factoring and by formula, the discriminant, the vertex, and the best weight of a model.42 min
  24. Exponentials: growth and decay FreeThe same factor each step, the number e, and decaying learning rates.43 min
  25. Logarithms: the power question FreeTo what power?, the laws of logs, and adding log-probabilities instead of multiplying.45 min
  26. Sequences and Σ FreeArithmetic and geometric sequences, Σ as a loop that adds, and mean squared error.40 min
  27. Weighted and moving averages FreeWeights that add to 1, a window average, the exponential moving average, and smoothing a loss curve.35 min
  28. Sets, and reading the symbols FreeSets, union and intersection, ℝⁿ and f : ℝⁿ → ℝᵐ, and reading a paper's first equation.41 min
  29. Review: find the slip (algebra) FreeBroken algebra and code to fix, mixed practice from the whole module, and its formula sheet.34 min
  30. Transposing step by step: undo in reverse order FreeA formula's layers, the opposite of each, peeling from the outside in, conditions, and round-trip checks.35 min
  31. Formulas with fractions: clear them first FreeClearing denominators, cross-multiplying, a letter in the bottom, and reciprocal formulas like 1/R = 1/R₁ + 1/R₂.35 min
  32. When the letter appears twice: collect and factor FreeGathering the letter on one side, factoring it out, dividing by the bracket, and rearranging precision and F1.35 min
  33. Squares, roots and powers FreeSquare roots with ±, squaring to undo a root, cube and nth roots, and the √d inside attention.40 min
  34. When the letter is squared and plain: quadratics FreeRearranging into ax² + bx + c = 0, the formula, completing the square, and choosing the root that fits.35 min
  35. Letters in the power: exponentials and logarithms FreeTaking logs to bring a power down, exponentiating to free a letter, and the logit that undoes the sigmoid.40 min
  36. Rearranging inequalities: when the sign flips FreeThe four moves on an inequality, negatives and reciprocals that flip it, logs below 1, and sample sizes.35 min
  37. Inverse functions, lines and scaling FreeUndoing a function by making x the subject, domains that allow it, line forms, and unscaling predictions.40 min
  38. Sequences and sums: find n, a, d and r FreeEvery letter of the arithmetic and geometric formulas as the subject, and an average's window from its decay.40 min
  39. Combining formulas: substitute and eliminate FreePutting one formula inside another to remove a letter, and sizing a training run from a time or money budget.35 min
  40. Review: rearrange anything (algebra) FreeBroken rearrangements to fix, mixed practice from the whole algebra block, a strategy chart, and its formula sheet.35 min
  41. Coordinates and distance FreePoints as (x, y), Pythagoras, distance in any number of coordinates, and nearest neighbors.42 min
  42. Angles, degrees and radians FreeMeasuring a turn, converting units, arcs, and the angle between two arrows.36 min
  43. Sine and cosine FreeAcross and up: right triangles, the unit circle, and directions and rotations.42 min
  44. Waves: height, speed and shift FreeAmplitude, period and phase, sampling a wave, and position codes in transformers.37 min
  45. Review: find the slip (shapes and waves) FreeBroken geometry and code to fix, mixed practice from the module, and its formula sheet.29 min
  46. Angles, triangles and waves: rearranging with sin, cos and tan FreeSides and angles from SOH CAH TOA, principal values, arcs, polar coordinates, and a wave's time and period.45 min
  47. Vectors: lists of numbers that point FreeA list, a point and an arrow; components, dimension, NumPy arrays, and data as vectors.42 min
  48. Adding and scaling vectors FreeComponent-wise sums, scalar multiples, mixes, and the weight update w − ηg.43 min
  49. Length and distance: norms FreeL2, L1 and max norms, unit vectors, distance, and the norms inside losses and clipping.42 min
  50. The dot product FreeMultiply in pairs and add; a·a as squared length; a @ b; one neuron as a dot product.43 min
  51. Angle, cosine similarity and projection FreeDirection without length, perpendicular vectors, shadows, and search by meaning.45 min
  52. Perpendicular directions: bases and coordinates FreeOrthonormal directions, coordinates as dot products, rebuilding a vector, and taking a direction out.35 min
  53. Matrices: tables of numbers FreeRows, columns and entries; two-dimensional arrays and slices; a data set as a matrix.41 min
  54. Adding, scaling and transposing matrices FreeEntry-by-entry sums and scalings, the transpose, mean images, and tables turned around.36 min
  55. A matrix times a vector FreeEach row dotted with the vector, the size rule, A @ x, and a layer acting on one example.42 min
  56. Matrix multiplication FreeRow meets column, the size rule, order matters, and a batch through a layer: X W + b.45 min
  57. Identity, diagonal, triangular and symmetric FreeFour patterns and their jobs: rescaling, distance tables, and the causal mask.37 min
  58. Matrices as movements of space FreeStretches, flips, shears and rotations; columns as landing spots; chaining; a layer moving data.42 min
  59. Determinant and inverse FreeThe area factor ad − bc, singular matrices, undoing a matrix, and redundant features.42 min
  60. Solving systems by elimination FreeAugmented matrices, row moves, back-substitution, the three outcomes, and fitting weights.45 min
  61. Independence, span and rank FreeRedundant vectors, span, rank, outer products, and low-rank updates like LoRA.42 min
  62. Eigenvectors: directions that only stretch FreeAv = λv, checking candidates, np.linalg.eig, and the main direction of a data cloud.41 min
  63. SVD and PCA: the important directions first FreeA matrix as pieces by size, the best rank-k copy, compression, and PCA maps of data.45 min
  64. Tensors, shapes and broadcasting FreeAxes and shapes, reshape, axis=, broadcasting, and shapes through a small model.43 min
  65. One-hot vectors and lookup tables: embeddings FreeA one-hot row picks a table's row, a sentence looked up as vectors, and a score for every word.35 min
  66. Sliding dot products: convolution FreeA small pattern slid along a list and over a grid, output sizes, stride and padding, and shared weights.40 min
  67. Review: find the slip (vectors and matrices) FreeShape slips to fix, mixed practice from the module, and its formula sheet with shapes.36 min
  68. Vector equations: rearranging with arrows FreeSolving for a vector or a scale, recovering a gradient from two weight snapshots, and an angle from a dot product.40 min
  69. Matrix equations: multiply by the inverse, on the correct side FreeNo dividing by a matrix: inverses from the left or right, order, transposes, and the normal equations.40 min
  70. Rates of change FreeChange over change, secants, rates from readings with np.diff, and reading a loss curve.41 min
  71. Limits: what a value heads toward FreeApproaching from both sides, holes, corners and jumps, epsilon, and judging activations.37 min
  72. The derivative: slope at a point FreeShrinking secants, f′(x) and dy/dx, Δy ≈ f′Δx, and which way a weight should move.45 min
  73. Derivative rules FreeConstants, powers, multiples, sums, eˣ and ln x, checked numerically, and a squared error's slope.41 min
  74. The product rule and the chain rule FreeProducts and chains of functions, forward then backward, and one neuron's dL/dw.45 min
  75. Lowest points and curvature Freef′ = 0, the second-derivative test, tables, local and global minima, and convex losses.43 min
  76. Standing in for a curve near a point FreeTangent lines, a curvature term, growing error, and why learning rates must be small.37 min
  77. Partial derivatives FreeOne input at a time, ∂, nudging in Python, and the two slopes of a line's loss.41 min
  78. The gradient FreeAll the slopes as a vector, steepest climb and descent, a numerical gradient, and the loss gradient.42 min
  79. Gradient descent FreeStepping against the gradient, the learning rate, a training loop, and fitting a line.45 min
  80. Faster descent: momentum and Adam FreeMomentum and Adam by hand, the bias correction, and three optimizers down one narrow valley.40 min
  81. The chain rule with many paths: backpropagation by hand FreeGraphs, multiply along paths and add across them, gradient checks, and a 2-2-1 network by hand.45 min
  82. Automatic differentiation: how PyTorch finds every slope FreeA tape of steps walked backward, and requires_grad, backward(), .grad, zero_grad() and no_grad().40 min
  83. Jacobians and Hessians FreeSlopes of vector functions, a layer's Jacobian, second partials, and bowls, domes and saddles.42 min
  84. Integrals: adding up thin slices FreeStrip and trapezoid sums, summing undoes differencing, probability as area, and AUC.43 min
  85. Review: find the slip (calculus) FreeCalculus slips to fix, mixed practice from the module, and its formula sheet.36 min
  86. Rearranging in calculus: slopes, steps and constants FreeSetting a slope to zero, Newton's step, the chain rule turned around, constants from a point, and learning rates.45 min
  87. Counting: choices, orders and groups FreeThe counting principle, factorials, ordered picks and groups, and why attention's cost grows with the square of the length.43 min
  88. Probability: from counts to chances FreeEqually likely outcomes, the complement, distributions, seeded simulation, and a next-word model.43 min
  89. Combining events: and, or, independent FreeThe or rule, independence, probability trees, drawing with and without replacement, and chains of steps.42 min
  90. Conditional probability and Bayes' rule FreeConditionals from tables, why P(A | B) isn't P(B | A), Bayes' rule, and precision and recall.45 min
  91. Random variables and distributions FreeUncertain numbers, the probability of a range, sampling by slices, and sampling versus argmax.42 min
  92. Expected value, variance and standard deviation FreeProbability-weighted averages, spread in the data's own units, and a training loss as an expected value.42 min
  93. Bernoulli, binomial, uniform and normal FreeYes-or-no trials, counts of yeses, the 68-95-99.7 rule, z-scores, and an accuracy's error bar.45 min
  94. Two variables at once: covariance and correlation FreeJoint tables and marginals, covariance, correlation, the covariance matrix, and features that carry the same information.45 min
  95. Review: find the slip (probability) FreeProbability slips to fix, mixed practice from the module, and its formula sheet.36 min
  96. Probability formulas: solve for the missing chance FreeConditionals, Bayes' rule for the prior, the or rule, expected values, variance, and z-scores turned around.45 min
  97. Describing data: center, spread and scale FreeMean, median and mode, variance and standard deviation, percentiles, outliers, and standardizing features.42 min
  98. Samples, the law of large numbers and the central limit theorem FreeSamples and populations, the standard error σ/√n, the bell of averages, and error bars on test scores.43 min
  99. Is the difference real? Comparing two models FreePaired differences, a bootstrap interval, what a p-value is and isn't, and why many tries make lucky wins.40 min
  100. Maximum likelihood FreeLikelihoods as products, log-likelihoods as sums, grid search, underflow, and the negative log-likelihood loss.45 min
  101. Linear regression: the best line FreeResiduals, least squares by formula, three roads to one line, the matrix form, and train versus test error.45 min
  102. Logistic regression: a line that answers yes or no FreeThe sigmoid, the log loss, its slope p − y, a training loop, and choosing a threshold.45 min
  103. Scoring a classifier: confusion table, precision, recall, F1 FreeThe four cells, accuracy, precision, recall and F1, and what moving a threshold does to each.35 min
  104. Softmax: scores into probabilities FreeExponentiate and share out, shifting and temperature, the safe softmax, and a classifier's last step.43 min
  105. Surprise, entropy and cross-entropy FreeSurprise in bits, entropy, cross-entropy and KL divergence, perplexity, and a language model's loss.45 min
  106. KL divergence: how far one distribution is from another FreeKL by hand, cross-entropy as entropy plus KL, why it isn't symmetric, and a soft-target loss.35 min
  107. Review: find the slip (statistics and information) FreeStatistics slips to fix, mixed practice from the module, and its formula sheet.38 min
  108. Statistics and information: n, z, logits and bits FreeSample sizes from error bars, inputs from probabilities, logit gaps from softmax, and chances from bits and losses.40 min
  109. One neuron, start to finish FreeWeighted sum, activation, loss, slopes and update, by hand and in code, and what one straight line can and can't split.45 min
  110. A layer and a small network as matrices FreeTwo layers on a batch, the shape of every matrix, adding a hidden unit, and XOR solved.45 min
  111. Training a small network FreeThe backward pass in matrix form, gradient checks, a full training loop, and reading loss curves.45 min
  112. The same network in PyTorch Freenn.Sequential with the NumPy weights loaded, the same loss and slopes, then SGD and mini-batches.45 min
  113. Attention as matrix math FreeScaled dot-product scores, the causal mask, a row-by-row softmax, and blending value vectors.45 min
  114. Residual connections and layer norm FreeAdding the input back and why its slope keeps learning alive, layer norm by hand, and add and norm.40 min
  115. A transformer block, start to finish FreeA sentence through embeddings, attention, add and norm, a small network and next-word scores, every shape named.45 min
  116. Planning a model: rearranging the formulas of a working network FreeLayer widths from parameter counts, sizes from memory and compute, the attention scale, and a training plan.40 min
  117. Final test: transpose any formula FreeSlips to fix from every topic, mixed practice of every kind of rearranging, the strategy chart and the full sheet.45 min
  118. Capstone: a sign reader from the formulas FreeBuild, train and test a trail-sign classifier with NumPy alone, and report its accuracy with an error bar.45 min
Part of a free course 118 lessons

The Foundation Math For Ai & ML: from arithmetic to attention

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.

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