Settings

Theme
Lite Mode (saves mobile data)

In Lite Mode, animations and videos don't play until you tap them, and their size is shown first. Interactive widgets still work.

Text size

Back up or move your progress →

Part 1: Math FoundationsProbability and Statistics

Statistical thinking for ML

P1.D1345 min●●○ IntermediateReviewed Dec 1, 2026

Why this matters for machine learning

Every number a model reports is measured on a random sample, so you need to know how far to trust it before you say that one model beats another or ship a change.

  • Is model B really better than model A? Every evaluation metric (P3.A9) is measured on a sample of test examples, so a gap of one or two points can be noise; this lesson shows how to put an interval on the gap and test it fairly. (P3.A9: Evaluation metrics, coming soon)
  • A held-out test set gives an honest estimate only if it is not used to choose among many models, which is why data is split into training, validation and test sets and why cross-validation exists. (P3.A4: Train, validation and test sets, coming soon)
  • Hyperparameter search tries many settings, and the best score of many tries is inflated by luck, so the winner must be checked on data the search never saw. (P4.23: Hyperparameter tuning, coming soon)
  • Benchmark scores of language models are averages over finite question sets, so a leaderboard gap smaller than the noise says little; contamination of the test questions breaks the independence these formulas assume. (P10.G1: Evaluating LLMs, coming soon)
  • Leaked or duplicated examples make test scores look better than they are and make the error bars too narrow. (P3.A11: Features, scaling and data leakage, coming soon)
  • Experiments in a team are logged with seeds and configurations so that results can be repeated, compared and given error bars. (P12.3: Experiment tracking and reproducibility, coming soon)

Before this: Covariance and the multivariate Gaussian, Law of large numbers and the Central Limit Theorem, Descriptive statistics and visualization

After this lesson you can

  • Say what a standard error and a 95%95\% confidence interval are, build xˉ±1.96 s/n\bar x\pm1.96\,s/\sqrt n and an interval for a test accuracy, and state what the 95%95\% does and does not mean
  • Explain a hypothesis test: the null hypothesis, the test statistic, the p-value (and what it is not), type I and type II errors, power, and why α=0.05\alpha=0.05 is a convention
  • Compute 1−0.95k1-0.95^k for kk tests, explain p-hacking and reuse of a test set, and tell a significant gap from an important one
  • Compare two models fairly (same test set, a paired test, several seeds, an interval for the gap), and explain why correlation is not causation and what a randomized experiment fixes

Twenty teams each test an idea on a fresh test set of 10001000 examples. None of the ideas works: every version of the model has the same true accuracy, 0.800.80. Each team compares its new model with the old one using the usual test at the 5%5\% level, and announces a result if the test says the difference is significant. How likely is it that at least one team announces one? A common first guess is about 5%5\%. The answer, as this lesson shows, is 64%64\%. The usual test is not broken. It is doing exactly what it promises for one team, and the surprise comes from asking twenty times.

This lesson is about the gap between a number measured on a sample and the truth behind it: how to put an error bar on it, how to decide whether a difference is real, how to compare two models fairly, and why a pattern in data does not say what causes it. Most of what follows rests on one fact from P1.D8: an average over a random sample is itself random, with a spread that shrinks like 1/n1/\sqrt n.

An estimate is not the truth

A model has a true accuracy pp: the share of correct answers over all the data it could meet. You do not see pp. You see a test set of nn examples, which is a random sample (P1.D9), and its measured accuracy p^\hat p (read “p-hat”). The measured value is an estimate of pp. It is also the maximum-likelihood estimate of pp (P1.D10). With another random test set you would get another p^\hat p.

How far off is a typical estimate? Each test example is correct (11) or wrong (00), so p^\hat p is an average of nn Bernoulli draws, and its standard error (the standard deviation of the estimate, P1.D8) is p(1−p)/n\sqrt{p(1-p)/n}. For a true accuracy of 0.800.80:

test examples nnstandard errora typical test set lands within about ±1.96\pm1.96 standard errors
1001000.0400.040±0.078\pm0.078
100010000.01260.0126±0.025\pm0.025
10,00010{,}0000.00400.0040±0.0078\pm0.0078

The standard deviation describes how spread out the data are. The standard error describes how spread out the estimate is, and it shrinks as nn grows. These formulas assume the test examples are independent draws from the kind of data you care about. When that fails (the same user appears many times, or test examples were copied from the training set) the true error bar is wider than the formula says. A later section returns to this.

Confidence intervals

The simplest honest report is the estimate with an error bar. For the average of nn independent values with sample standard deviation ss (P1.D12), and nn large enough for the central limit theorem to work (P1.D8), the 95%95\% confidence interval is

xˉ±1.96 sn.\bar x\pm1.96\,\frac{s}{\sqrt n}.

The number 1.961.96 is the Gaussian value with 95%95\% of the probability within it (P1.D3). (P1.D8 wrote the spread as σ\sigma; in practice you do not know it and use ss.) Other levels use other values: 1.6451.645 for 90%90\% and 2.5762.576 for 99%99\%. For an accuracy the average is of 0/10/1 values, so the interval is

p^±1.96p^(1−p^)n.\hat p\pm1.96\sqrt{\frac{\hat p(1-\hat p)}{n}}.

A model is right on 842842 of 10001000 test examples. Then p^=0.842\hat p=0.842, the standard error is 0.842×0.158/1000=0.0115\sqrt{0.842\times0.158/1000}=0.0115, and the interval is 0.842±0.02260.842\pm0.0226, from 0.8190.819 to 0.8650.865. To halve the width you need four times as many examples, the 1/n1/\sqrt n law again.

What “95%” means

Here is the careful statement. The true accuracy pp is a fixed number. The interval is computed from random data, so it changes from one test set to the next. If you repeated the whole procedure (draw a test set, compute the interval) many times, about 95%95\% of the intervals would contain pp. The 95%95\% is a property of the procedure. For one finished interval, such as 0.8190.819 to 0.8650.865, the true value is either inside it or not, and the frequentist reading (P1.D6) does not attach a probability to that. The widget below draws 100100 intervals so you can see the procedure at work.

One hundred confidence intervals

True accuracy of the model, p

Test examples, n

True accuracy 0.8, 200 test examples: 93 of 100 intervals cover it, 7 miss. In the long run the share that cover is 94.1%, close to the 95% the recipe promises.
0.70.80.91measured accuracy (one test set per row)

interval covers p ◆ interval misses p true accuracy p accuracy 1, the largest possible

intervals that cover p = 93 of 100 intervals that miss p = 7 long-run share that cover (exact) = 94.1% intervals reaching above 1 = 0 test sets with every example right (a zero-width interval at 1) = 0

Each row is a fresh test set of n independent examples. The exact long-run share adds up the binomial probabilities of the counts whose interval covers p. The count of 100 changes from one draw to the next; the exact share does not. Segments are cut at the edge of the picture.

One hundred confidence intervals. A model has a true accuracy p (the green vertical line). Each row is a fresh test set of n independent examples, and the row shows its measured accuracy as a dot and its interval p-hat plus and minus 1.96 standard errors as a segment. Blue thin rows cover p. Red thick rows with a diamond miss p. Choose p and n, and press Draw 100 new intervals for a new seed (the draws are seeded, so the first picture is the same for everyone). The readouts count the hits and misses in the picture and give the exact long-run share of intervals that cover p, computed by adding up binomial probabilities.

Three common misreadings are wrong. The interval is not the range holding 95%95\% of the test examples, since the individual examples are 00 or 11 and the interval is about their average. It does not say the model is right 95%95\% of the time. And it is not a 95%95\% chance that a particular finished interval holds the truth. A Bayesian interval (a credible interval, from the posterior of P1.D6 and P1.D11) does make a probability statement about the parameter, but it rests on a prior and answers a different question.

Things to try

  1. Leave p=0.8p=0.8 and n=200n=200 and draw several times. The count of intervals that cover pp changes from draw to draw, usually between about 9090 and 9898 out of 100100 (the first draw has 9393), and the exact long-run share is 94.1%94.1\%. The red intervals are not arithmetic mistakes: the procedure allows a few misses.
  2. Choose n=1000n=1000: the intervals become less than half as wide as at n=200n=200 (the standard error shrinks by 5\sqrt5, about 2.22.2), and the share that cover stays near 95%95\%. More data narrows the interval but does not raise the coverage.
  3. Choose p=0.95p=0.95 and n=20n=20. The exact long-run share that cover is only 63.9%63.9\%. On average about 3636 of every 100100 test sets have all 2020 examples right, so p^=1\hat p=1 and the interval is a single point at 11, which misses p=0.95p=0.95. Raise nn to 10001000 and the share returns to 94.2%94.2\%.

When the interval fails

The recipe uses a Gaussian approximation, and it is poor when the accuracy is close to 00 or 11, or nn is small. With 1919 of 2020 right, p^=0.95\hat p=0.95 and the interval is 0.8540.854 to 1.0461.046, above the largest possible accuracy. With 2020 of 2020 right the interval has width zero: it claims certainty after 2020 examples. The exact coverage of the nominal 95%95\% interval, computed from the binomial distribution, shows the pattern.

true accuracy ppn=20n=20n=1000n=1000
0.800.8092.1%92.1\%94.7%94.7\%
0.950.9563.9%63.9\%94.2%94.2\%

A common rule of thumb asks for at least about 1010 right and 1010 wrong answers before trusting the simple interval. For the other cases, use a better interval (the Wilson interval, named in the box below) or a bootstrap.

Go deeper Small samples: the t-interval, and the Wilson interval

When nn is small and ss must be estimated from the data, the interval xˉ±1.96 s/n\bar x\pm1.96\,s/\sqrt n is too narrow, because ss itself is uncertain. The fix replaces 1.961.96 by a larger value from the tt distribution, which depends on the degrees of freedom n−1n-1. For five training seeds with accuracies 0.81,0.79,0.83,0.80,0.820.81,0.79,0.83,0.80,0.82 (made up), the mean is 0.8100.810, s=0.0158s=0.0158 and s/5=0.00707s/\sqrt5=0.00707. The tt value for 44 degrees of freedom is 2.7762.776, so the interval is 0.810±0.01960.810\pm0.0196, from 0.7900.790 to 0.8300.830. The Gaussian value 1.961.96 would give 0.7960.796 to 0.8240.824, too narrow. The tt value falls toward 1.961.96 as nn grows (2.2622.262 at 99 degrees of freedom, 2.0452.045 at 2929). The tt-interval assumes the values are roughly Gaussian.

For an accuracy, the Wilson interval keeps the coverage close to 95%95\% over a much wider range. For 2020 of 2020 right it gives 0.8390.839 to 1.0001.000 instead of the useless point at 11, and for 842842 of 10001000 it gives 0.8180.818 to 0.8630.863, close to the simple interval. Its formula is longer and is not derived here; libraries provide it.

Hypothesis tests and p-values

A confidence interval says which values of the truth fit the data. A hypothesis test asks one yes-or-no question: could this result be just noise?

Take two models. A is right on 800800 of 10001000 test examples and B on 830830 of another 10001000 (made up). The gap is 33 points. Is it real? The test works by contradiction.

  1. State the null hypothesis, H0H_0: the two models have the same true accuracy, so any gap is luck.
  2. Compute a test statistic: here the gap divided by its standard error under H0H_0. Under H0H_0 the best single estimate of the common accuracy is the pooled value pˉ=0.815\bar p=0.815 (16301630 correct answers out of 20002000). The standard error of the gap is then 2pˉ(1−pˉ)/1000=0.0174\sqrt{2\bar p(1-\bar p)/1000}=0.0174, and the statistic is z=0.03/0.0174=1.73z=0.03/0.0174=1.73.
  3. Find the p-value. Assuming H0H_0, the statistic follows approximately a Gaussian curve, and the probability of a result at least 1.731.73 standard errors from 00 in either direction is 0.0840.084.

The p-value is the probability, computed assuming the null hypothesis and the model assumptions are true, of getting a result at least as extreme as the one observed. Here, if the models were equal, about 8.4%8.4\% of experiments like this would show a gap of 33 points or more in one direction or the other. A small p-value means the data would be surprising under the null. The usual rule is to call the result significant when the p-value is below a chosen level α\alpha, most often α=0.05\alpha=0.05. The 8.4%8.4\% here is above 0.050.05, so this experiment does not reject the null.

The interval for the gap tells the same story with more detail. Its standard error (computed from the two measured accuracies, not pooled) is

0.8×0.21000+0.83×0.171000=0.0174,\sqrt{\frac{0.8\times0.2}{1000}+\frac{0.83\times0.17}{1000}}=0.0174,

and the interval is 0.030±0.0340.030\pm0.034, from −0.004-0.004 to 0.0640.064. It includes 00 (consistent with no difference) and also includes a gap of 66 points. “Not significant” is not “no difference”: the experiment is too small to tell.

What a p-value is not

  • It is not the probability that the null hypothesis is true. A p-value of 0.0840.084 does not mean an 8.4%8.4\% chance that the models are equal. It is computed assuming they are equal. To get the probability of the null you also need a prior, as in Bayes’ theorem (P1.D6). Suppose 10%10\% of the ideas you test truly help, your test has power 0.80.8 (below), and you use α=0.05\alpha=0.05. Out of 10001000 ideas, 8080 true winners are caught and 4545 of the 900900 useless ideas pass by luck, so 36%36\% of the significant results are false alarms.
  • It is not the size of the effect. A p-value mixes the gap with nn: a tiny gap gives a tiny p-value when nn is huge.
  • It is not the probability that the result will repeat.
  • α=0.05\alpha=0.05 is a convention, not a law of nature. It is a habit; some fields use 0.010.01 or a stricter level, and a threshold turns a smooth measure of surprise into a sharp yes or no.

A permutation test reaches a p-value without a formula. If the two models were equal, which model produced each outcome would not matter, so shuffle the 20002000 outcomes between the two labels many times and see how often a gap as large as 33 points arises by chance. For this example about 9%9\% of shuffles do, close to the 0.0840.084 above (the code cell below runs it).

Two ways to be wrong, and power

A test can make two kinds of mistake.

the models really are equalB is really better
test says “significant”type I error: a false alarm (chance α\alpha by design)a correct detection
test says “not significant”correcttype II error: a miss (chance β\beta)

The power of a test, 1−β1-\beta, is the chance that it detects a real gap of a given size. It grows with nn and with the size of the gap, and shrinks as α\alpha is made stricter. P1.D8 asked how many test examples tell a model with 90%90\% accuracy from one with 91%91\%. Take n=6604n=6604 examples per model, the number at which a one-point gap equals 1.961.96 standard errors. When the true gap is exactly one point, the test catches it only about half the time. The table shows the power of the test for true accuracies 0.900.90 and 0.910.91 (Gaussian approximation, separate test sets).

examples per modelpower
1000100012%12\%
3000300026%26\%
6604660450%50\%
10,00010{,}00067%67\%
13,50013{,}50080%80\%
20,00020{,}00093%93\%

To catch this gap four times out of five you need about 13,50013{,}500 examples per model. Designing an experiment means choosing nn before looking at the result so that the power is acceptable for the smallest gap you care about.

Try it: how often are you fooled?

Here is the opening puzzle as an experiment. Model A has true accuracy 0.800.80. Model B has 0.800.80 plus a true gap that you choose, and the gap starts at zero, so the models are the same. A study makes kk comparisons, each with two fresh test sets of nn examples, and counts how often the test calls the gap significant.

How often are you fooled?

10010,000
0: same models+5 points

Comparisons per study, k

Same true accuracy 0.8 for both models, so every significant result is a false alarm. Of 1000 studies of 1 comparison on 1000 test examples each, 5.2% had at least one false alarm (theory 5%).
050100150−505gap B − A (accuracy points)

looks the same looks significant ±1.96 standard errors (3.5 points) true gap Gaussian prediction

The first 50 studies (each square is one study of 1 comparison)

✕ filled: at least one significant result in the study. Empty: none. Here 1 of 50.

comparisons that look significant, simulated = 5.2% theory (the 5% level) = 5% studies with at least one, simulated = 5.2% theory 1 − (1 − 0.05)1 = 5% average per study, simulated = 0.05 theory k × 0.05 = 0.05 gap needed to look significant = ±3.5 points seed = 7

Each comparison draws two independent test sets, one per model, and calls a gap significant when the pooled z-test gives |z| above 1.96. The k comparisons in a study are independent. Simulated shares come from 1000 studies and wobble by up to about 3 points from one seed to the next; the theory values use the Gaussian approximation and do not change.

How often are you fooled? Model A has true accuracy 0.80 and model B has 0.80 plus the true gap. Each comparison draws a test set of n examples for each model (exact binomial counts) and applies the two-sided z-test at the 5 percent level. A study makes k comparisons, and 1000 studies are run for the chosen settings. The histogram shows the observed gap, B minus A, in the first comparison of each study: blue bars are gaps that look the same, hatched pink bars look significant, the dashed lines mark plus and minus 1.96 standard errors under no difference, the dotted green line is the true gap and the black curve is the Gaussian prediction. The row of squares shows the first 50 studies, with a cross in each study that has at least one significant comparison. The readouts put simulated shares next to theory. Slide n and the true gap, choose k, draw a new seed or reset. Nothing moves by itself, so Lite Mode changes nothing.
  1. One comparison of equal models. With the true gap 00, n=1000n=1000 and k=1k=1, about 5%5\% of the comparisons look significant. These are false alarms, and the hatched bars sit in the two tails of the histogram, beyond the dashed lines.
  2. More data does not remove false alarms. Move nn to 10,00010{,}000. The dashed lines move in to ±1.1\pm1.1 points, but the share of false alarms stays near 5%5\%. A significance level of 5%5\% means 5%5\% false alarms whatever nn is; nn only sets how small a gap can be seen.
  3. Many comparisons. Set k=5k=5: the share of studies with at least one false alarm is about 22.6%22.6\% (1−0.9551-0.95^5). Set k=20k=20: about 64%64\%, and a study has on average one significant result among its twenty. That is the opening puzzle.
  4. A real gap. Set the true gap to +2+2 points with k=1k=1. The share of comparisons that look significant is the power: 20.7%20.7\% at n=1000n=1000, 72.2%72.2\% at n=5000n=5000 and 95.0%95.0\% at n=10,000n=10{,}000. At n=1000n=1000 about four of every five studies miss a real two-point improvement, and the histogram shows why: the bulk of the bars lies between the dashed lines.
  5. A small gap. At +1+1 point and n=10,000n=10{,}000 the power is only 43%43\%.

The simulated numbers come from 10001000 studies, so they wobble by up to about three points from the theory; press New seed to see the wobble.

Many tries, and the test set that gets used up

Look at what the widget showed for k=20k=20. A single test at α=0.05\alpha=0.05 is a good tool, and twenty tests are a different tool. For kk independent tests of true nulls, the chance of at least one false alarm is 1−(1−0.05)k1-(1-0.05)^k:

number of tests kk11552020100100
chance of at least one false alarm0.050.050.2260.2260.6420.6420.9940.994

This is the multiple comparisons problem. It shows up whenever you try many models, many hyperparameter settings, many features, many subgroups or many metrics. The simplest remedy is Bonferroni’s correction: use the level α/k\alpha/k for each test, here 0.05/20=0.00250.05/20=0.0025. Then the chance of at least one false alarm is at most α\alpha, even when the tests depend on each other. The price is lower power per test. (The formula 1−0.95k1-0.95^k assumes independent tests; tests that share data are correlated and the exact number differs, but the problem stays.)

P-hacking is trying analyses until one gives p<0.05p<0.05 and reporting only that one. It does not need bad intent: this is the “garden of forking paths”, where each choice (which subset, which metric, which outliers to drop) looks reasonable, but together they give many chances to find noise. The protection is to decide the comparison, the metric and the stopping rule before looking at the result, and to say how many things were tried.

The same logic spoils a test set. The test set is meant to give one honest estimate of how the final model performs on new data (P3.A4). Each time you look at the test score and then change the model, the test set takes part in the choice, and the estimate becomes optimistic. A model chosen as the best of 2020 looks better than it is. Suppose 2020 models all have true accuracy 0.800.80 and each is measured on 10001000 test examples. The measured accuracies are about Gaussian with spread 0.01260.0126, and the expected best of twenty draws is 1.871.87 standard deviations above the mean: about 0.8240.824 by this Gaussian estimate (0.8230.823 in an exact simulation) instead of 0.800.80. A fresh test set removes the effect: the winner measured again scores 0.800.80 on average. This fall of an extreme performer back toward the average is regression to the mean (P1.D7), and the optimism in the winner’s first score is sometimes called the winner’s curse. The remedies are to tune on a validation set, touch the test set once at the end (P3.A4), and confirm important winners on fresh data.

Significant is not the same as important

The p-value mixes the size of a gap with the sample size. Suppose two models have true accuracies 0.8000.800 and 0.8020.802, and each is tested on 1,000,0001{,}000{,}000 examples. The standard error of the gap is 0.000560.00056, so a typical result has zz near 3.53.5 and p≈0.0004p\approx0.0004: highly significant. If the measured gap is exactly 0.0020.002, the interval is 0.00090.0009 to 0.00310.0031, about a tenth to a third of a percentage point. Whether that matters depends on the application and the cost of switching. The reverse also happens: a 33 point gap on 10001000 examples is not significant, as shown above, though a 33 point gain might matter a lot.

So report the effect size (the gap, in accuracy points) with its confidence interval, not just “p<0.05p<0.05”. The interval shows the plausible range, so a reader can judge practical significance (is the gain worth having?) as well as statistical significance (is it distinguishable from zero?).

Comparing two models fairly

Collecting the pieces gives a short checklist for “is B better than A?”.

  1. Same test set. Evaluate both models on the same examples, so that differences come from the models and not from easier or harder data.
  2. Use the pairing. Two models usually make many of the same mistakes. On the same 10001000 examples, suppose both models are right on 760760, only A is right on 4040, only B is right on 7070, and both are wrong on 130130 (made up). Model A scores 800/1000=0.800800/1000=0.800 and B scores 830/1000=0.830830/1000=0.830, the same accuracies as in the example above. Only the 110110 examples where the models disagree carry information about which is better. McNemar’s test asks whether 7070 against 4040 looks like a fair coin: χ2=(70−40)270+40=8.18\chi^2=\frac{(70-40)^2}{70+40}=8.18, and the p-value is 0.0040.004 (from the chi-square approximation; an exact binomial test on the 110110 disagreements gives 0.0050.005). The paired gap has standard error about 0.01040.0104 (the code cell prints 0.01050.0105 because it divides by n−1n-1) and interval 0.0100.010 to 0.0500.050. The same accuracies, tested as if the test sets were separate, gave p=0.084p=0.084. Pairing removes the noise from easy and hard examples that both models handle the same way. It also answers the question left open in P1.D8: for this pattern of agreement the paired standard error is 0.01040.0104 instead of 0.01740.0174, so the same precision needs about 2.82.8 times fewer examples. (A paired bootstrap reaches the same interval without a formula: resample the examples with replacement and recompute the gap many times. The code cell below finds 0.0090.009 to 0.0510.051.)
  3. Report the gap with its interval, not two accuracies side by side.
  4. Test-set noise is not the only noise. A test tells how much the test set can mislead for models that are fixed. Training is random too: another seed gives another model. Train each model with several seeds and report the median or the mean with the spread (P1.D12). If A gives 0.81,0.79,0.83,0.80,0.820.81,0.79,0.83,0.80,0.82 and B gives 0.83,0.82,0.84,0.81,0.830.83,0.82,0.84,0.81,0.83 over five seeds each (made up), B’s mean is 1.61.6 points higher, but the interval for the gap (Welch’s tt method) runs from −0.4-0.4 to +3.6+3.6 points. Five seeds cannot tell. Add seeds, and say how many you used.
  5. Count what you tried. If B was the winner of 2020 variants, apply the corrections above.
  6. Say what was not tested. The formulas assume independent test examples from the data you care about. A better score on the benchmark does not mean a better score after the data drift (P12.5).

Correlation is not causation

P1.D7 showed that a correlation of 0.90.9 between two variables says they move together, not why. There are three common reasons for a pattern.

  • A confounder drives both variables. Suppose heavy users of an app are shown a new feature 80%80\% of the time and light users 20%20\%, half of all users are heavy, heavy users buy 50%50\% of the time and light users 10%10\%, and the feature itself has no effect. Then the buy rate is 0.8×0.5+0.2×0.1=0.420.8\times0.5+0.2\times0.1=0.42 among users who saw the feature and 0.2×0.5+0.8×0.1=0.180.2\times0.5+0.8\times0.1=0.18 among those who did not. A strong association appears with a feature that does nothing. Stratifying by user type (the idea of P1.D5’s Simpson’s paradox box) removes it when the confounder is recorded, and cannot when it is not.
  • Reverse causation: the outcome causes the “cause”. A city with more police officers can have more recorded crime, because extra officers were sent where crime was already high.
  • Selection bias: the way the data were collected links the variables. If a data set contains only papers that were published, it can show that a method works better than it does, because failures were not published.

The fix is a randomized experiment. Let a coin decide who gets the feature. The coin is independent of everything else, so heavy and light users are spread equally over both groups, and a remaining difference is caused by the feature (up to noise). In the example above, the randomized buy rates are 0.300.30 and 0.300.30. An A/B test of two models in production works this way: randomly send users to model A or model B and compare an outcome. It still needs enough users. With 50005000 users per group and click rates 10.0%10.0\% and 11.0%11.0\%, the gap is one point, z=1.63z=1.63 and p=0.10p=0.10, and the interval runs from −0.2-0.2 to +2.2+2.2 points. Detecting this gap with power 0.80.8 needs about 14,70014{,}700 users per group.

Two links to statistical errors come back later. Data leakage (P3.A11) puts test information into training or duplicates examples across the split, so the test score is too good, and the standard error is too small because the examples are no longer independent. In the extreme case where the 10001000 test examples are 100100 different examples, each copied ten times, they carry the information of 100100, and the true standard error is 0.0400.040 instead of the 0.01260.0126 the formula gives, about 3.23.2 times larger. And distribution shift means the future data is not the population the test set sampled.

Where this shows up in machine learning

  • Is B really better than A? Put an interval on the gap. Gaps of a point or two on a few thousand test examples are often within noise, and a paired test on the same examples is the fair tool (the metrics themselves are P3.A9).
  • Splits and cross-validation. The validation set is for choosing and the test set is for one final honest estimate. Cross-validation repeats the split to reduce the noise of a single split (P3.A4).
  • Hyperparameter search. Searching over many settings inflates the best score, so report the winner on data the search never touched (P4.23).
  • Benchmarks and leaderboards. Scores are averages over finite question sets, so each has a standard error, and ranks that differ by less than the noise are not a real ordering. Questions seen during training (contamination) break the assumptions (P10.G1).
  • A/B tests in production. Models are compared on live traffic by random assignment, with the sample size chosen from the power calculation (deployment is P12.4, monitoring is P12.5).
  • Error bars everywhere. Report several seeds, a spread and an interval; log the seeds and the configuration so the result can be repeated (P12.3).

Intuition

A measurement is a dart thrown at the truth. One dart tells you roughly where the target is, and the spread of many darts tells you how much to trust one. A confidence interval is a net that is cast around your one dart, sized so that the net would catch the target in 95%95\% of throws; once it is cast, the target is in it or it is not. A p-value is the question “how surprised would I be if the two models were identical?” Small surprise means the gap could be luck. Twenty tickets in a lottery win more often than one, and twenty tests find a winner more often than one test. The analogy breaks in one place: a lottery ticket has a fixed chance, while the chance that a significant result is a false alarm depends on how many ideas were really worth testing.

Math

Standard error. For independent values with standard deviation σ\sigma: SE(xˉ)=σ/n\mathrm{SE}(\bar x)=\sigma/\sqrt n, estimated by s/ns/\sqrt n. For an accuracy, SE(p^)=p(1−p)/n\mathrm{SE}(\hat p)=\sqrt{p(1-p)/n}.

Interval. estimate±z⋅SE\text{estimate}\pm z\cdot\mathrm{SE}, with z=1.96z=1.96 for 95%95\%.

Two accuracies on separate test sets. With pˉ\bar p the pooled accuracy,

z=p^B−p^A2pˉ(1−pˉ)/n,z=\frac{\hat p_B-\hat p_A}{\sqrt{2\bar p(1-\bar p)/n}},

and the p-value is 2(1−Φ(∣z∣))2\bigl(1-\Phi(|z|)\bigr). The interval for the gap is (p^B−p^A)±1.96 SE1(\hat p_B-\hat p_A)\pm1.96\,\mathrm{SE}_1, with SE1=p^A(1−p^A)/n+p^B(1−p^B)/n\mathrm{SE}_1=\sqrt{\hat p_A(1-\hat p_A)/n+\hat p_B(1-\hat p_B)/n}.

McNemar. With n01n_{01} examples where only B is right and n10n_{10} where only A is right, χ2=(n01−n10)2n01+n10\chi^2=\dfrac{(n_{01}-n_{10})^2}{n_{01}+n_{10}} is compared with a chi-square distribution with one degree of freedom (the square of a standard Gaussian).

Power. Write δ\delta for the true gap, SE0\mathrm{SE}_0 for the standard error under no difference and SE1\mathrm{SE}_1 for the true standard error of the gap. The two-sided test rejects when ∣gap∣>1.96 SE0|\text{gap}|>1.96\,\mathrm{SE}_0, so

power=Φ ⁣(δ−1.96 SE0SE1)+Φ ⁣(−δ−1.96 SE0SE1).\begin{aligned} \text{power}&=\Phi\!\Bigl(\frac{\delta-1.96\,\mathrm{SE}_0}{\mathrm{SE}_1}\Bigr)\\ &\quad+\Phi\!\Bigl(\frac{-\delta-1.96\,\mathrm{SE}_0}{\mathrm{SE}_1}\Bigr). \end{aligned}

For a power of 80%80\% the sample size per model is about

n=(1.96+0.8416)2 Vδ2,n=\frac{(1.96+0.8416)^2\,V}{\delta^2},

where V=pA(1−pA)+pB(1−pB)V=p_A(1-p_A)+p_B(1-p_B).

Many tests. For kk independent tests of true nulls, P(at least one false alarm)=1−(1−α)k\mathbb{P}(\text{at least one false alarm})=1-(1-\alpha)^k. Bonferroni uses α/k\alpha/k per test; the union bound gives a total of at most α\alpha whatever the dependence.

Best of kk. For kk independent standard Gaussian errors, the expected maximum is 1.871.87 for k=20k=20.

Code

Compare two models with NumPy. The first lines are a z-test, and the last lines are the paired quantities from the same examples.

import numpy as np
from math import sqrt

a, b, n = 800, 830, 1000                        # examples right, separate test sets
pbar = (a + b) / (2 * n)
z = (b - a) / n / sqrt(2 * pbar * (1 - pbar) / n)   # 1.73

only_a, only_b = 40, 70                         # same test set: examples where only one is right
chi2 = (only_b - only_a) ** 2 / (only_a + only_b)  # McNemar: 8.18

Try it: intervals, tests and simulations in code

The first cell builds the interval for 842842 of 10001000, the z-test, the paired McNemar test, a permutation test and a paired bootstrap for the examples above. The second cell runs the simulations: the best of twenty equal models, how often at least one of kk tests is significant, the coverage of the interval at several accuracies and sample sizes, and the confounded and randomized buy rates. Predict each output before you run it. The simulated numbers use a seeded generator, so they repeat; they differ from the theory values by sampling noise.

Try it: intervals, z-test, McNemar, permutation test, bootstrap

Runs real Python in your browser. First run downloads about 9 MB (once; your browser keeps it).

Try it: how often you are fooled, interval coverage, a confounder

Runs real Python in your browser. First run downloads about 9 MB (once; your browser keeps it).

The outputs repeat because the generators are seeded. In the first cell, the unpaired p-value of 0.0840.084 becomes 0.00420.0042 in the paired test on the same examples. In the second cell, the average best-of-twenty accuracy is 0.8230.823, and the winners fall back to 0.8000.800 on fresh data. At 0.950.95 with 2020 examples the interval covers only about 63%63\% of the time, and the confounded buy rates (0.4180.418 against 0.1800.180) become equal under randomization.

Go deeper The bootstrap, and why a bootstrap is not magic

The bootstrap estimates how an estimate would vary by resampling the data you have. Draw nn examples with replacement from the nn test examples, recompute the statistic (an accuracy, a gap between two models on the same examples) and repeat thousands of times. The middle 95%95\% of the recomputed values is a percentile interval. It needs no formula, so it also works for statistics like the F1 score or the AUC (P3.A9), where the standard error has no simple expression. It assumes the examples are independent and the sample is large enough to look like the population: with a tiny sample, or a statistic that depends on extreme values (the maximum), it can be too narrow. Resample whole groups (all rows of one user) when rows are not independent.

Common mistakes

Check your understanding

  1. A test accuracy has a 95%95\% confidence interval of 0.8190.819 to 0.8650.865 (large nn, independent examples). Which statement correctly describes what the confidence level means?

  2. Two models are compared and the test gives a p-value of 0.030.03. What does the p-value say?

  3. You compare 2020 independent pairs of models whose members all have the same true accuracy, each pair with the usual test at the 5%5\% level. What is the chance that at least one pair looks significantly different?

  4. Models A and B are tested on the same 10001000 examples. Both are right on 760760, only A on 4040, only B on 7070, and both are wrong on 130130. Which examples does McNemar’s test use to decide whether B is better?

  5. Heavy users of an app are shown a new feature more often and also buy more. Which study best tests whether the feature causes more purchases?

Exercises

  1. A model is right on 360360 of 400400 test examples. Give the standard error of its accuracy and an approximate 95%95\% interval.
    Show answerp^=0.9\hat p=0.9, SE=0.9×0.1/400=0.015\mathrm{SE}=\sqrt{0.9\times0.1/400}=0.015, and 1.96×0.015=0.02941.96\times0.015=0.0294, so the interval is about 0.8710.871 to 0.9290.929. This assumes independent examples; with 0.90.9 and 400400 examples the Gaussian approximation is reasonable.
  2. How many independent test examples give a 95%95\% interval of half-width 0.020.02 for an accuracy near 0.80.8?
    Show answern=1.962×0.8×0.2/0.022≈1537n=1.96^2\times0.8\times0.2/0.02^2\approx1537. Halving the half-width to 0.010.01 needs four times as many, about 61476147.
  3. You run 2020 independent tests at α=0.05\alpha=0.05 on true nulls. What is the chance of no false alarm, and of at least one? What per-test level does Bonferroni use? And for 100100 tests?
    Show answerNone: 0.9520=0.3580.95^{20}=0.358. At least one: 0.6420.642. Bonferroni uses 0.05/20=0.00250.05/20=0.0025. For 100100 tests the chance of at least one false alarm is 1−0.95100=0.9941-0.95^{100}=0.994, and Bonferroni would use 0.00050.0005.
  4. Model A is right on 350350 of 500500 examples and model B on 370370 of another 500500. Give the z statistic, the two-sided p-value and the interval for the gap.
    Show answerThe pooled accuracy is 0.720.72 and SE0=2×0.72×0.28/500=0.0284\mathrm{SE}_0=\sqrt{2\times0.72\times0.28/500}=0.0284, so z=0.04/0.0284=1.41z=0.04/0.0284=1.41 and p=0.159p=0.159. The interval is 0.04±1.96×0.02840.04\pm1.96\times0.0284, from −0.016-0.016 to 0.0960.096. Not significant, and consistent with gaps from slightly negative to nearly ten points.
  5. On the same test set, only A is right on 2525 examples and only B on 4545. Compute McNemar’s χ2\chi^2 and the p-value.
    Show answerχ2=(45−25)2/70=5.71\chi^2=(45-25)^2/70=5.71, and the p-value is 0.0170.017 (chi-square approximation; the exact binomial test gives 0.0220.022). B wins 4545 of the 7070 disagreements, which a fair coin would rarely do.
  6. True accuracies are 0.800.80 and 0.820.82 and each model is tested on 10001000 independent examples. What is the power of the 5%5\% test?
    Show answerAbout 0.2070.207, so roughly four of five such experiments miss a real two-point gap. Use the widget with the gap at +2+2 points and n=1000n=1000 to check.
  7. Each of two models is tested on 2,000,0002{,}000{,}000 examples, with accuracies 0.8000.800 and 0.8010.801. Is the gap significant, and is it important?
    Show answerWith pooled accuracy 0.80050.8005, SE0=0.0004\mathrm{SE}_0=0.0004, z=2.50z=2.50 and p=0.012p=0.012, so it is significant at 0.050.05. The gap is a tenth of a percentage point, with an interval of about 0.00020.0002 to 0.00180.0018. Whether that is important depends on the cost of switching and on what an extra 0.10.1 point is worth.
  8. Cities with more ice-cream sales have more drownings. Name a likely confounder and say how an experiment could test whether ice cream causes drownings.
    Show answerHot weather drives both: more people swim and more people buy ice cream. A randomized experiment would give ice cream to randomly chosen people and compare drowning rates. In practice, you would instead compare cities or days with the same temperature, which works only if the confounder is measured.
  9. The best of 2020 model variants scores 0.840.84 on a test set of 10001000 examples used to pick it, and all variants have true accuracy 0.800.80. What accuracy do you expect on a fresh test set, and what is the standard error of that measurement?
    Show answerAbout 0.800.80: the extra 0.040.04 is selection luck (the expected best of twenty is about 0.8230.823, and this winner was luckier than usual). The standard error of one accuracy measurement is 0.8×0.2/1000=0.0126\sqrt{0.8\times0.2/1000}=0.0126.
  10. The interval for the gap between two models is −0.4-0.4 to +6.4+6.4 points. Is the gap significant at the 5%5\% level? What would you do next?
    Show answerThe interval contains 00, so the two-sided test at 5%5\% does not reject. But the interval also contains gaps large enough to matter, so the experiment is inconclusive rather than negative. Collect more test examples (or use a paired comparison on the same examples) so that the interval narrows.

Next: P1.E1 turns surprise into a number: information and entropy. In Part 3, evaluation metrics (P3.A9) and the train, validation and test split with cross-validation (P3.A4) apply these tools, leakage (P3.A11) shows how test scores become too good, hyperparameter search (P4.23) meets the multiple comparisons problem, and experiment tracking (P12.3) records the seeds that give error bars.

Key takeaways

  • A number measured on a sample (a test accuracy, a mean) is an estimate of the true value, and a new sample gives a different estimate. Its typical error is the standard error, p(1−p)/n\sqrt{p(1-p)/n} for an accuracy and s/ns/\sqrt n for a mean. It holds when the examples are independent draws from the data you care about.
  • A 95%95\% confidence interval for large nn is the estimate ±1.96\pm1.96 standard errors. The 95%95\% describes the procedure: if you repeated the whole experiment many times, about 95%95\% of the intervals would hold the true value. It is not a 95%95\% chance for one finished interval, and it is not the share of the data inside it. The interval for an accuracy fails when p^\hat p is near 00 or 11 or nn is small.
  • A hypothesis test asks how surprising the data would be if there were no true difference (the null hypothesis). The p-value is the probability, computed under the null, of a result at least as extreme as the one seen. It is not the probability that the null is true. The level α=0.05\alpha=0.05 is a convention. A type I error is a false alarm (rate α\alpha), a type II error is a miss, and power is the chance of catching a real gap; it grows with nn and with the size of the gap.
  • Try many things and some win by luck: for kk independent tests at α=0.05\alpha=0.05 the chance of at least one false alarm is 1−0.95k1-0.95^k (0.640.64 for k=20k=20). The best of many equal models looks better than it is, and the test set is used up by repeated looks. Decide the comparison first, divide α\alpha by kk (Bonferroni), and confirm a winner on fresh data.
  • Significant does not mean important: with enough data a 0.20.2 point gap is significant, and with too little a large gap is not. Report the gap and its interval. Compare two models on the same test set with a paired test such as McNemar’s, which uses only the examples where they differ, and report several training seeds with their spread.
  • Correlation is not causation. A confounder can drive both variables, the direction can be reversed, and a selected sample can create a link. A randomized experiment (an A/B test) breaks the link, and it still needs enough users to separate a real gap from noise.
Found a mistake? Tell us