Twenty teams each test an idea on a fresh test set of examples. None of the ideas works: every version of the model has the same true accuracy, . Each team compares its new model with the old one using the usual test at the 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 . The answer, as this lesson shows, is . 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 .
An estimate is not the truth
A model has a true accuracy : the share of correct answers over all the data it could meet. You do not see . You see a test set of examples, which is a random sample (P1.D9), and its measured accuracy (read “p-hat”). The measured value is an estimate of . It is also the maximum-likelihood estimate of (P1.D10). With another random test set you would get another .
How far off is a typical estimate? Each test example is correct () or wrong (), so is an average of Bernoulli draws, and its standard error (the standard deviation of the estimate, P1.D8) is . For a true accuracy of :
| test examples | standard error | a typical test set lands within about standard errors |
|---|---|---|
The standard deviation describes how spread out the data are. The standard error describes how spread out the estimate is, and it shrinks as 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 independent values with sample standard deviation (P1.D12), and large enough for the central limit theorem to work (P1.D8), the confidence interval is
The number is the Gaussian value with of the probability within it (P1.D3). (P1.D8 wrote the spread as ; in practice you do not know it and use .) Other levels use other values: for and for . For an accuracy the average is of values, so the interval is
A model is right on of test examples. Then , the standard error is , and the interval is , from to . To halve the width you need four times as many examples, the law again.
What “95%” means
Here is the careful statement. The true accuracy 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 of the intervals would contain . The is a property of the procedure. For one finished interval, such as to , 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 intervals so you can see the procedure at work.
Three common misreadings are wrong. The interval is not the range holding of the test examples, since the individual examples are or and the interval is about their average. It does not say the model is right of the time. And it is not a 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
- Leave and and draw several times. The count of intervals that cover changes from draw to draw, usually between about and out of (the first draw has ), and the exact long-run share is . The red intervals are not arithmetic mistakes: the procedure allows a few misses.
- Choose : the intervals become less than half as wide as at (the standard error shrinks by , about ), and the share that cover stays near . More data narrows the interval but does not raise the coverage.
- Choose and . The exact long-run share that cover is only . On average about of every test sets have all examples right, so and the interval is a single point at , which misses . Raise to and the share returns to .
When the interval fails
The recipe uses a Gaussian approximation, and it is poor when the accuracy is close to or , or is small. With of right, and the interval is to , above the largest possible accuracy. With of right the interval has width zero: it claims certainty after examples. The exact coverage of the nominal interval, computed from the binomial distribution, shows the pattern.
| true accuracy | ||
|---|---|---|
A common rule of thumb asks for at least about right and 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 is small and must be estimated from the data, the interval is too narrow, because itself is uncertain. The fix replaces by a larger value from the distribution, which depends on the degrees of freedom . For five training seeds with accuracies (made up), the mean is , and . The value for degrees of freedom is , so the interval is , from to . The Gaussian value would give to , too narrow. The value falls toward as grows ( at degrees of freedom, at ). The -interval assumes the values are roughly Gaussian.
For an accuracy, the Wilson interval keeps the coverage close to over a much wider range. For of right it gives to instead of the useless point at , and for of it gives to , 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 of test examples and B on of another (made up). The gap is points. Is it real? The test works by contradiction.
- State the null hypothesis, : the two models have the same true accuracy, so any gap is luck.
- Compute a test statistic: here the gap divided by its standard error under . Under the best single estimate of the common accuracy is the pooled value ( correct answers out of ). The standard error of the gap is then , and the statistic is .
- Find the p-value. Assuming , the statistic follows approximately a Gaussian curve, and the probability of a result at least standard errors from in either direction is .
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 of experiments like this would show a gap of 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 , most often . The here is above , 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
and the interval is , from to . It includes (consistent with no difference) and also includes a gap of 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 does not mean an 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 of the ideas you test truly help, your test has power (below), and you use . Out of ideas, true winners are caught and of the useless ideas pass by luck, so of the significant results are false alarms.
- It is not the size of the effect. A p-value mixes the gap with : a tiny gap gives a tiny p-value when is huge.
- It is not the probability that the result will repeat.
- is a convention, not a law of nature. It is a habit; some fields use 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 outcomes between the two labels many times and see how often a gap as large as points arises by chance. For this example about of shuffles do, close to the 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 equal | B is really better | |
|---|---|---|
| test says “significant” | type I error: a false alarm (chance by design) | a correct detection |
| test says “not significant” | correct | type II error: a miss (chance ) |
The power of a test, , is the chance that it detects a real gap of a given size. It grows with and with the size of the gap, and shrinks as is made stricter. P1.D8 asked how many test examples tell a model with accuracy from one with . Take examples per model, the number at which a one-point gap equals 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 and (Gaussian approximation, separate test sets).
| examples per model | power |
|---|---|
To catch this gap four times out of five you need about examples per model. Designing an experiment means choosing 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 . Model B has plus a true gap that you choose, and the gap starts at zero, so the models are the same. A study makes comparisons, each with two fresh test sets of examples, and counts how often the test calls the gap significant.
- One comparison of equal models. With the true gap , and , about 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.
- More data does not remove false alarms. Move to . The dashed lines move in to points, but the share of false alarms stays near . A significance level of means false alarms whatever is; only sets how small a gap can be seen.
- Many comparisons. Set : the share of studies with at least one false alarm is about (). Set : about , and a study has on average one significant result among its twenty. That is the opening puzzle.
- A real gap. Set the true gap to points with . The share of comparisons that look significant is the power: at , at and at . At 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.
- A small gap. At point and the power is only .
The simulated numbers come from 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 . A single test at is a good tool, and twenty tests are a different tool. For independent tests of true nulls, the chance of at least one false alarm is :
| number of tests | ||||
|---|---|---|---|---|
| chance of at least one false alarm |
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 for each test, here . Then the chance of at least one false alarm is at most , even when the tests depend on each other. The price is lower power per test. (The formula 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 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 looks better than it is. Suppose models all have true accuracy and each is measured on test examples. The measured accuracies are about Gaussian with spread , and the expected best of twenty draws is standard deviations above the mean: about by this Gaussian estimate ( in an exact simulation) instead of . A fresh test set removes the effect: the winner measured again scores 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 and , and each is tested on examples. The standard error of the gap is , so a typical result has near and : highly significant. If the measured gap is exactly , the interval is to , 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 point gap on examples is not significant, as shown above, though a point gain might matter a lot.
So report the effect size (the gap, in accuracy points) with its confidence interval, not just “”. 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?”.
- Same test set. Evaluate both models on the same examples, so that differences come from the models and not from easier or harder data.
- Use the pairing. Two models usually make many of the same mistakes. On the same examples, suppose both models are right on , only A is right on , only B is right on , and both are wrong on (made up). Model A scores and B scores , the same accuracies as in the example above. Only the examples where the models disagree carry information about which is better. McNemar’s test asks whether against looks like a fair coin: , and the p-value is (from the chi-square approximation; an exact binomial test on the disagreements gives ). The paired gap has standard error about (the code cell prints because it divides by ) and interval to . The same accuracies, tested as if the test sets were separate, gave . 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 instead of , so the same precision needs about 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 to .)
- Report the gap with its interval, not two accuracies side by side.
- 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 and B gives over five seeds each (made up), B’s mean is points higher, but the interval for the gap (Welch’s method) runs from to points. Five seeds cannot tell. Add seeds, and say how many you used.
- Count what you tried. If B was the winner of variants, apply the corrections above.
- 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 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 of the time and light users , half of all users are heavy, heavy users buy of the time and light users , and the feature itself has no effect. Then the buy rate is among users who saw the feature and 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 and . 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 users per group and click rates and , the gap is one point, and , and the interval runs from to points. Detecting this gap with power needs about 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 test examples are different examples, each copied ten times, they carry the information of , and the true standard error is instead of the the formula gives, about 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 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 : , estimated by . For an accuracy, .
Interval. , with for .
Two accuracies on separate test sets. With the pooled accuracy,
and the p-value is . The interval for the gap is , with .
McNemar. With examples where only B is right and where only A is right, is compared with a chi-square distribution with one degree of freedom (the square of a standard Gaussian).
Power. Write for the true gap, for the standard error under no difference and for the true standard error of the gap. The two-sided test rejects when , so
For a power of the sample size per model is about
where .
Many tests. For independent tests of true nulls, . Bonferroni uses per test; the union bound gives a total of at most whatever the dependence.
Best of . For independent standard Gaussian errors, the expected maximum is for .
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.18Try it: intervals, tests and simulations in code
The first cell builds the interval for of , 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 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.
Runs real Python in your browser. First run downloads about 9 MB (once; your browser keeps it).
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 becomes in the paired test on the same examples. In the second cell, the average best-of-twenty accuracy is , and the winners fall back to on fresh data. At with examples the interval covers only about of the time, and the confounded buy rates ( against ) 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 examples with replacement from the test examples, recompute the statistic (an accuracy, a gap between two models on the same examples) and repeat thousands of times. The middle 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
A test accuracy has a confidence interval of to (large , independent examples). Which statement correctly describes what the confidence level means?
The belongs to the procedure: over repeated test sets, about of the intervals cover the fixed true value. For one finished interval the true value is inside or it is not, so a probability of for this interval is a misreading. The model was right on about of the examples (), not . Individual examples are or , so none lies between and .
Two models are compared and the test gives a p-value of . What does the p-value say?
A p-value is a probability computed under the null hypothesis of equal accuracy: how often a result this extreme would arise from luck alone. It is not the probability that the null hypothesis is true, which needs a prior. It says nothing about the size of the gap, which can be tiny when is huge. And it is not a probability of replication.
You compare independent pairs of models whose members all have the same true accuracy, each pair with the usual test at the level. What is the chance that at least one pair looks significantly different?
Each test is right about the null with probability , so all twenty are right with probability , and at least one false alarm has probability . The value is the rate for one test. The value is the chance of no false alarm at all. Twenty tests are not a guarantee of a false alarm: more than a third of such studies produce none.
Models A and B are tested on the same examples. Both are right on , only A on , only B on , and both are wrong on . Which examples does McNemar’s test use to decide whether B is better?
On an example where both models are right, or both wrong, neither model gains on the other, so it adds nothing to the question of which is better. The disagreements are a coin-flip experiment under the null hypothesis: if the models were equal, B would win about half of them. Here B won against . Using all examples equally would treat the agreements as information, which they are not.
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?
Random assignment makes heavy and light users equally common in both groups, so a remaining difference can be credited to the feature. A larger sample of the confounded comparison shrinks the noise but keeps the bias. A high correlation is what a confounder produces. Comparing buyers with non-buyers looks backward from the outcome and still mixes in who the users are.
Exercises
- A model is right on of test examples. Give the standard error of its accuracy and an approximate interval.
Show answer
, , and , so the interval is about to . This assumes independent examples; with and examples the Gaussian approximation is reasonable. - How many independent test examples give a interval of half-width for an accuracy near ?
Show answer
. Halving the half-width to needs four times as many, about . - You run independent tests at 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 tests?
Show answer
None: . At least one: . Bonferroni uses . For tests the chance of at least one false alarm is , and Bonferroni would use . - Model A is right on of examples and model B on of another . Give the z statistic, the two-sided p-value and the interval for the gap.
Show answer
The pooled accuracy is and , so and . The interval is , from to . Not significant, and consistent with gaps from slightly negative to nearly ten points. - On the same test set, only A is right on examples and only B on . Compute McNemar’s and the p-value.
Show answer
, and the p-value is (chi-square approximation; the exact binomial test gives ). B wins of the disagreements, which a fair coin would rarely do. - True accuracies are and and each model is tested on independent examples. What is the power of the test?
Show answer
About , so roughly four of five such experiments miss a real two-point gap. Use the widget with the gap at points and to check. - Each of two models is tested on examples, with accuracies and . Is the gap significant, and is it important?
Show answer
With pooled accuracy , , and , so it is significant at . The gap is a tenth of a percentage point, with an interval of about to . Whether that is important depends on the cost of switching and on what an extra point is worth. - 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 answer
Hot 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. - The best of model variants scores on a test set of examples used to pick it, and all variants have true accuracy . What accuracy do you expect on a fresh test set, and what is the standard error of that measurement?
Show answer
About : the extra is selection luck (the expected best of twenty is about , and this winner was luckier than usual). The standard error of one accuracy measurement is . - The interval for the gap between two models is to points. Is the gap significant at the level? What would you do next?
Show answer
The interval contains , so the two-sided test at 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.