Stage I · Bachelor's: Foundations
Part 10 of 65Significance
When is a pattern too strong to be chance?
In 1710 Arbuthnot finds more boys than girls christened in London in each of 82 years, a (1/2)^82 event if every year were a fair coin; in 1935 Fisher's lady has 1 chance in 70 of picking out four milk-first cups by guessing. The part builds Fisher's logic (a null, a statistic, a tail probability) and the exact tests that randomization itself supplies, from the tea to Darwin's maize and the permutation machine, and proves the p-value uniform under the null. Neyman and Pearson add the alternative: two kinds of error, power, and the lemma that the likelihood ratio gives the most powerful test, found here as a knapsack over all 2,048 rejection regions of a dice problem. The likelihood ratio test with Wilks' theorem, the everyday z and t tests, Welch's repair and Pearson's chi-squared follow, with Mendel's peas fitting too well. Then the part turns to how tests go wrong: too little power, peeking after every observation (29% false alarms by n = 100), reading p as the probability of the null, and testing many things at once.
What you need. Counting (binomial coefficients), and from earlier parts: the t, chi-squared and F distributions of Part 8 and the likelihood of Part 9.
- Hook
- Arbuthnot 1710; the lady tasting tea
- Mathematics
- p-values, Neyman–Pearson, the likelihood ratio, z/t/χ²/exact tests, power, Welch, the peeking problem
- Built
- a permutation machine
What you will be able to do
Bachelor's
- Carry out a sign test, Fisher's exact test and a t-test, and state the null hypothesis each one tests.
- Say what a p-value is, and explain why it is not the probability that the null is true.
Master's
- Prove that a p-value is uniform under a continuous null, and prove the Neyman-Pearson lemma for simple hypotheses.
- Derive the likelihood ratio statistic for a one-parameter model and compare it with the Wald and score tests on the same data.
PhD
- State when a uniformly most powerful test exists (a monotone likelihood ratio, a one-sided alternative), and what a randomization test needs from the design to be valid without a model.
Practice
- Compute the sample size for a stated power, and the type S and type M errors of an underpowered study.
- Recognize what breaks a test's size (peeking, a pooled variance with unequal spreads, many tests) and name the repair for each.
Contents
Each chapter has a home level. Choose a track to see what to read and watch: Bachelor's 35 min · Master's 62 min · PhD 62 min · Practice 47 min.
- 0More boys than girls, and a cup of teaBachelor's3 min
- 1Fisher's logicBachelor's6 min
- 2Exact tests by designBachelor's7 min
- 3The p-valueBachelor's4 min
- 4Two kinds of errorBachelor's4 min
- 5The Neyman-Pearson lemmaMaster's5 min
- 6The likelihood ratio testMaster's5 min
- 7The everyday testsBachelor's4 min
- 8Pearson's chi-squaredMaster's5 min
- 9Power and sample sizePractice4 min
- 10The peeking problemPractice4 min
- 11What p-values are notBachelor's5 min
- 12Many testsPractice4 min
- Recap, problems, and the road aheadAll tracks3 min
Also on this page: Lecture · Key results · Try it · Lab · Problems · Notes and sources · Build the film.
Lecture
The text of each chapter is the film's narration, as it is spoken, so you can read along or revise without the film. The pictures are in the film.
More boys than girls, and a cup of teaBachelor's3 min
In 1710, John Arbuthnot, physician to Queen Anne, satirist and friend of Jonathan Swift, read a paper to the Royal Society with a theological title: an argument for divine providence, taken from the constant regularity in the births of both sexes. He had the London christening records for the eighty-two years from 1629 to 1710, and in every single year more boys had been christened than girls. Suppose, he said, that years are independent, each like a fair coin, equally likely to favour boys or girls. Then the chance of boys winning eighty-two years in a row is one half to the power eighty-two: about two in ten to the twenty-five. Chance can't explain it, he concluded; it must be art, by which he meant Providence.
Here are his data. Each dot is a year, and its height is the share of the year's christenings that were boys. The plague years, the Civil War and the Great Fire are all in there, and the numbers swing, from about fifty point three to fifty-three point six percent. But every dot is above one half. Eighty-two plus signs. Over the whole period, nearly four hundred and eighty-five thousand boys and four hundred and fifty-four thousand girls. Arbuthnot's argument has every ingredient of a modern significance test: a null hypothesis, that each year is a fair coin; a statistic, the number of years boys won; and the probability, under the null, of a result at least that extreme. His conclusion about Providence, we'll come back to.
Two centuries later, at the Rothamsted agricultural station in the 1920s, a colleague of Fisher's, the algologist Muriel Bristol, declined a cup of tea because the milk had been poured in after the tea. She said she could taste the difference. Fisher told the story in 1935, in the second chapter of The Design of Experiments, as the model of how to test such a claim. Prepare eight cups, four with the milk first and four with the tea first, and present them in random order. She must pick out the four milk-first cups. There are seventy ways to choose four cups out of eight. If she can't taste anything, each is equally likely, and she gets all four right with probability one in seventy, under one and a half percent. According to the story, told decades later by a witness, she got every cup right. But the design, not the result, was Fisher's point: the randomization itself creates the null distribution.
What it does: Arbuthnot's paper and his 82 years plotted; the tea; objectives.; Numbers (computed): male share 0.503–0.536; 484,382 boys, 453,841 girls; p = 2.07 × 10⁻²⁵; 1/70
1Fisher's logicBachelor's6 min
Arbuthnot's argument, and the tea, share a structure that Fisher made into a method. First, a null hypothesis: a specified claim and sampling model, here how the data would arise if nothing interesting were happening, if the years were coins or the lady were guessing. Second, a test statistic: a number computed from the data that tends to be large when the data disagree with the null. Third, the p-value: the probability, computed under the null, of a statistic at least as large as the one observed. For Arbuthnot, the statistic is the number of boys' years, and the p-value is two to the minus eighty-two. For the tea, the statistic is the number of milk-first cups correctly found, and the p-value is one in seventy. Notice what's absent: there's no alternative hypothesis anywhere. Fisher's test only asks how surprising the data are, if the null is true.
Here's the null distribution of a sign test, drawn for twenty years to keep it visible. If each year is a fair coin, the number of boys' years is binomial with twenty trials and probability one half: a symmetric hump around ten. Suppose boys had won fifteen years out of twenty. The p-value is the total height of the bars at fifteen and beyond: about two percent. Arbuthnot's case is the far end of a much longer row: eighty-two out of eighty-two, a single bar so small it's two to the minus eighty-two. The test throws away everything but the sign of each year, which is why it's called the sign test. It's the oldest significance test there is, and it still gets used, because it needs no model for the magnitudes. Its binomial calibration still needs independent signs with probability one half under the null, after ties are handled.
What does a small p-value license us to say? Fisher put it as a disjunction: either an exceptionally rare chance has occurred, or the theory of random distribution is not true. So a small p-value is evidence against the null, and the smaller it is, the stronger the evidence. For Fisher it was graded, not a yes-or-no verdict. And a large p-value is not evidence for the null. It may only mean the experiment was too small to see anything. In The Design of Experiments he wrote that the null hypothesis is never proved or established, but is possibly disproved, in the course of experimentation.
So did Arbuthnot prove Providence? His null was a fair coin each year. But across the eighty-two years, about fifty-one point six percent of christenings were boys. A year has about eleven thousand four hundred christenings, so in a simplified equal-year model with independent children, if each child is a boy with probability point five one six, boys win a given year with probability about point nine nine nine seven five, approximately. This illustration fixes every year at the average size; it does not fit the full pattern of historical annual counts. Over eighty-two years, that's a ninety-eight percent chance of a clean sweep. Under this chance model, what Arbuthnot saw was entirely expected. The lesson is the most important one in this part: rejecting a null hypothesis doesn't prove the alternative you had in mind. Arbuthnot rejected one particular chance model, a fair coin, not chance itself.
The point was made at the time. In 1712 the Dutch mathematician Willem 's Gravesande redid the argument with a finer statistic, the number of boys in each year, and still found a fair coin wanting. But Nicolaus Bernoulli, nephew of Jacob, replied that the yearly counts fit very well if each birth is like the throw of a die with thirty-five faces, eighteen of them marked boy. A biased probability model can explain a persistent male excess without Providence; whether it fits the full data is a separate question. It was the first argument over which null hypothesis to test, and it has never stopped.
Where does the famous five percent come from? In his 1925 textbook, Statistical Methods for Research Workers, Fisher noted that a normal deviate beyond one point nine six, or nearly two standard deviations, occurs by chance about one time in twenty. It is convenient, he wrote, to take this point as a limit in judging whether a deviation is to be considered significant. A convenience, a line at which to start taking a result seriously, not a law of nature. A year later he added that anyone wanting higher odds could draw the line at one in fifty, or one in a hundred. How a convenience became a rule is part of the story of the next chapters.
What it does: Null, statistic, p; the sign test; Fisher's disjunction; which null was rejected; 's Gravesande and Bernoulli; where 5% came from.; Numbers (computed): P(T ≥ 15 of 20) = 0.0207; per-year win 0.99975, all 82: 0.98
2Exact tests by designBachelor's7 min
Let's work out the tea test completely. If the lady is guessing, her four choices are a random four of the eight cups. The number of milk-first cups among them has a hypergeometric distribution, from Part 3: choose j of the four milk-first cups and four minus j of the others. The counts are one, sixteen, thirty-six, sixteen and one, out of seventy. All four right has probability one in seventy. That's the p-value if she gets them all. But three right, or better, has probability seventeen in seventy, about one in four. Fisher was explicit: with this design only a perfect score would count as evidence. One mistake, and it does not reject at five percent, though the result still contains information about her skill.
The design decides how much evidence is possible. With six cups, three of each, a perfect score has probability one in twenty under guessing: not much. With eight, one in seventy. With ten, one in two hundred and fifty-two; with twelve, one in nine hundred and twenty-four. More cups, more possible evidence. But consider a lady with real, imperfect skill, right about each cup with probability q, before enforcing the choice of exactly four milk-first cups by random tie-breaking. These power numbers depend on that response model. Simulating her sessions: if she's right seventy percent of the time, she achieves a perfect score with eight cups only eleven percent of the time; at eighty percent, a quarter of the time; even at ninety percent, only half. The test controls the chance of being fooled by a guesser, but it often fails to detect a genuine skill. That second kind of failure is what Neyman and Pearson would build their theory on, in chapter four.
Written as a table, the tea experiment is a two by two: the truth in the rows, her answers in the columns. A perfect score puts four on the diagonal and zero off it. Fisher's exact test works for any such table. Hold both sets of margins fixed: here, four of each kind of cup, and four of each answer. Then if rows and columns are independent, the top-left count has a hypergeometric distribution, and its tail probability is the p-value. No normal approximation is involved, so it's exact at any sample size, which is why it's still the standard test for small tables, in clinical trials and genetics.
Fisher's other example in 1935 was an experiment of Charles Darwin's. Darwin grew fifteen pairs of maize plants, one cross-fertilized and one self-fertilized in each pair, side by side in the same pots, and measured their heights. Here are the fifteen differences, cross minus self, in eighths of an inch. Thirteen favour the crossed plant, two the self-fertilized one. Their sum is three hundred and fourteen. Darwin had asked his cousin Francis Galton for help with the numbers. Fisher returned to them with a new idea.
Fisher's calculation uses sign-exchangeability under the null: for example, independent symmetric differences, or a sharp no-effect null with randomized assignments within pairs. Then within each pair, which plant ended up taller has nothing to do with how it was fertilized, and each difference was equally likely to come out positive or negative. So flip the signs. Here's one random flip; the sum changes. Here's another, and another. There are two to the fifteen, thirty-two thousand seven hundred and sixty-eight, sign patterns, all equally likely under the null. Compute the sum for every one of them, and that's the exact null distribution. The observed sum, three hundred and fourteen, is beaten or equalled by eight hundred and sixty-three of them: a one-sided p-value of two point six percent, and two-sided, five point three. Fisher counted them without a computer. Student's t-test, which assumes normality, gives point zero four nine seven, almost the same. Fisher's conclusion was that the t-test is justified as an approximation to the randomization test, in this dataset. Exact design-based validity needs the actual random assignment mechanism and a sharp null; a t approximation is not universally accurate for every data shape.
The same idea works for two separate groups, and here it is as a machine. Seven men from each of two of the World's regions, their heights rounded to the centimetre. Region A's average is two point seven centimetres below region B's. Is that a real difference? If the region makes no difference, the labels are arbitrary: any seven of these fourteen men could have been called A. So shuffle the labels. Deal the tokens into new seats, and recompute the difference. Again. And again. Each shuffle drops one dot onto the null distribution. There are three thousand four hundred and thirty-two ways to split fourteen into two sevens, so we can do them all. Our observed difference sits in the middle of the pile: more than half the splits are at least as extreme, so the p-value is point five six. No evidence of a difference. And the World knows the truth: the two regions' men average the same, to a tenth of a centimetre. Similar means do not establish identical distributions or prove the permutation null. This result fails to reject exchangeability; it does not establish it.
There's a deep point here about where null distributions come from. In the tea test and in a properly designed experiment, the experimenter randomized: for example, the order of the tea cups. For Darwin's historical data, do not assume an undocumented random assignment mechanism; the sign-flip calculation can instead be read under a symmetry model. Then the null distribution isn't a model at all. It's the randomization itself, which we know exactly because we did it. No assumption of normality, no model for the data: the test is valid by design. That was Fisher's great insight, and it's why he insisted on randomization. In the World's regions, nobody randomized which man lives where, so treating the labels as exchangeable under the null is an assumption about the world. Randomization inference returns with designed experiments in Part 13 and causal inference in Part 35, and permutation and rank tests in Part 16.
What it does: The tea's hypergeometric null; designs of 6–12 cups and the power of an imperfect taster; Fisher's exact test; Darwin's 15 pairs and all 2¹⁵ sign flips; the permutation machine on the World; randomization as the source of validity.; Numbers (computed): 1, 16, 36, 16, 1 /70; perfect-score power 0.11, 0.25, 0.51 at q = 0.7, 0.8, 0.9; Darwin p = 0.0263 / 0.0527 (t: 0.0497); regions p = 1,916/3,432 = 0.558
3The p-valueBachelor's4 min
Formally, the p-value is the probability, under the null, of a statistic at least as large as the one observed. As a function of the data, it's a statistic like any other. Before the data are collected, it's a random variable. So it has a sampling distribution, and we can ask what it is. That distribution is what gives the phrase p less than point zero five its meaning.
Here's the key fact. If the null is true and the statistic is continuous, the chance that the p-value is at most u is the chance that one minus F of T is at most u, that is, that F of T is at least one minus u. But F of T, a continuous random variable pushed through its own distribution function, is uniform: the probability integral transform, from Part 3, which Part 7 used to generate random numbers. So the chance is u. Under the null, the p-value is uniformly distributed between zero and one. Every value is equally likely. That's why rejecting when p is below point zero five makes a mistake exactly five percent of the time when the null is true.
Let's see it. Twenty thousand t-tests on samples of fifteen, with the null true. The p-values are flat across zero to one, and four point nine percent of them fall below point zero five. Now let the true mean be point three standard deviations away from the null. The p-values pile up toward zero, but only about one in five falls below point zero five. At point eight standard deviations, the pile is a spike near zero, and eighty-two percent fall below point zero five. The share of p-values below the line is the test's power: its chance of detecting a real effect. Under the null, the p-value is a uniform random number; under an alternative, it's a random number that tends to be small. Either way, it's random, which will matter a great deal in chapter eleven.
With a discrete statistic, the story changes slightly. In the tea test, only five p-values are possible: one in seventy, seventeen in seventy, fifty-three in seventy, sixty-nine in seventy, and one. Their distribution function is a staircase, and it never rises above the diagonal. The chance of a p-value at most u is at most u. Such p-values are called super-uniform. So a test that rejects when p is below point zero five really rejects only one time in seventy under the null. It's valid, since it never rejects more often than promised, but conservative. Part 11 will meet the same effect in intervals for proportions.
How surprising is a given p-value? A helpful translation, popularized by Sander Greenland, turns it into coin flips. Minus the log, base two, of p, measures the surprise in bits: a p-value of p is as surprising as that many fair coins all landing heads. A p-value of one half is one coin. Point zero five is four point three coins: about as surprising as four heads in a row, which is not very. The perfect tea score is six coins; Darwin's maize, a little over four. Point zero zero five is seven and a half. And Arbuthnot's eighty-two years are, of course, eighty-two coins. Thinking in coins is a useful antidote to treating point zero five as proof.
What it does: Definition; uniform under H₀ (proof); 20,000 t-tests at δ = 0, 0.3, 0.8; discrete super-uniform p; surprise in bits.; Numbers (computed): P(p < 0.05) = 0.049, 0.194, 0.819
4Two kinds of errorBachelor's4 min
Fisher's test has no alternative hypothesis. Two younger statisticians thought that was a mistake. Jerzy Neyman, a Polish mathematician who had come to Karl Pearson's laboratory in London in 1925, and Egon Pearson, Karl's son, argued in 1928 that a test can only be judged against the alternatives it's supposed to detect. In their 1933 paper on the most efficient tests of statistical hypotheses, they built a theory around two kinds of error. It became the textbook theory of testing, and it made Fisher furious.
A test ends in a decision: reject the null or don't. And the null is either true or false. That gives four cells. Two are correct. Rejecting a true null is a Type I error, a false alarm. Its probability is the size of the test, alpha. Failing to reject a false null is a Type II error, a miss. Its probability, beta, depends on how false the null is, and one minus beta is the power. Neyman and Pearson's recipe: fix the size in advance, say at five percent, and among all tests with that size, choose the one with the greatest power. Testing becomes an optimization problem.
Here's the picture for the simplest case, testing whether a normal mean is zero, against the alternative that it's some positive delta. The statistic's distribution under the null is the grey curve; under the alternative, the green one, shifted by delta times root n over sigma. Reject when the statistic exceeds a line. The red tail of the null curve beyond the line is alpha, the false-alarm rate. The part of the green curve below the line is beta, the miss rate. With the line at one point six four five, alpha is five percent and the power is eighty. Move the line right and false alarms drop, but misses rise. Move it left, and the reverse. For a fixed amount of data, the two errors trade against each other. To reduce both, pull the curves apart: collect more data, reduce measurement noise, or improve the design.
That gives a way to plan an experiment. For the two-sided z-test, the power has a formula, and it climbs with the sample size: here, for a true effect of half a standard deviation. Ignoring the far tail gives a standard planning approximation for n: the sum of two normal quantiles, times sigma over delta, squared. For eighty percent power you need thirty-two observations; for ninety, forty-three. Choosing the size of a study before running it, from the effect you want to be able to detect, is one of Neyman and Pearson's most lasting gifts. Chapter nine returns to it.
The two views are different philosophies. For Fisher, a test measures the evidence in this particular experiment against a hypothesis. You report the p-value, and its size grades the evidence. No alternative is needed. For Neyman, a test is a rule of behaviour: a procedure that, applied over many experiments, makes Type I errors at rate alpha and catches real effects at the rate of its power. You decide, reject or not, and you don't claim to have learned anything about this particular case. Modern practice is an awkward hybrid: compute Fisher's p-value, compare it with Neyman's alpha, and declare significance. The two men quarrelled bitterly for thirty years, and neither would have endorsed the hybrid.
What it does: Neyman & Pearson (1928, 1933); the decision table; sliding the cut; power against n; the two philosophies.; Numbers (computed): n = 32 (80%), 43 (90%) for δ = 0.5σ
5The Neyman-Pearson lemmaMaster's5 min
Which test is the most powerful? For the simplest case, one null distribution against one alternative, Neyman and Pearson answered completely. Reject when the likelihood ratio, the probability of the data under the alternative divided by its probability under the null, exceeds a constant. No test of the same size has more power. In words: rank every possible outcome by how much more likely it is under the alternative than under the null. Then reject for outcomes from the top of the ranking down, until you've spent your budget of false-alarm probability. It's a fractional knapsack problem when boundary randomization is allowed, and the likelihood ratio is value per unit weight. A greedy rule need not solve an arbitrary non-randomized knapsack.
A concrete example. Someone rolls two dice and tells you only the sum. Under the null, both dice are fair. Under the alternative, the second die is loaded, coming up six a third of the time. Here are the two distributions of the sum: grey for the null, green for the alternative. Under each sum, the likelihood ratio. Sums from two to six are a little less likely under the alternative; twelve is twice as likely. Think of each possible sum as an item you might put in your rejection region. Its weight is its null probability, which spends your size budget, and its value is its alternative probability, which buys power.
Now fill the knapsack. The budget is a size of one sixth. The best value for weight is a sum of twelve, with likelihood ratio two: it costs one thirty-sixth of size and buys two thirty-sixths of power. Next, eleven, with ratio one point four. Then ten, at one point two. That exactly spends the budget: size one sixth, and power point two three three. Is this really the best? There are only two thousand and forty-eight possible rejection regions, every subset of the eleven sums, so we can check them all. None with size at most one sixth has more power. Notice how weak even the best test is: with a single roll, the evidence is thin.
Here are all two thousand and forty-eight regions at once. Each dot is a possible test, placed by its size and its power. The orange line joins the regions the likelihood ratio builds, adding sums in order of their ratio. Every dot lies on or below it. Whatever size you're willing to accept, the likelihood ratio test sits on the frontier. The dashed diagonal is what you'd get by ignoring the data and rejecting at random with probability alpha. Between the corners of the frontier, a test can reach the edge by randomizing, which is what the lemma's clause about ties is for.
The proof is three lines. Let phi be the likelihood ratio test, and phi prime any rival whose size is no larger. At every outcome, the product of phi minus phi prime and p1 minus k p0 is at least zero. Where phi rejects, p1 exceeds k p0 and phi minus phi prime can't be negative. Where phi accepts, both factors are at most zero. Sum over all outcomes. The power difference is at least k times the size difference, which is at least zero. The likelihood ratio test wins.
What does the lemma say about everyday tests? For a normal mean with known sigma, the likelihood ratio between a positive delta and zero is an increasing function of x-bar. So the most powerful test rejects for large x-bar, and it's the same test whatever positive delta we had in mind. It's uniformly most powerful against all one-sided alternatives: the z-test is optimal. Samuel Karlin and Herman Rubin showed in 1956 that this happens whenever the likelihood ratio is monotone in a statistic. For this normal-mean model with two-sided alternatives no uniformly most powerful test exists, since the best test against positive deltas is the worst against negative ones. Part 46 develops the general theory.
What it does: Statement; two dice, one loaded; the knapsack; all 2,048 regions and the frontier; the proof; UMP one-sided tests.; Numbers (computed): best size-1/6 region {10, 11, 12}: power 0.233
6The likelihood ratio testMaster's5 min
The Neyman–Pearson lemma compares two single distributions. Most real hypotheses are composite: a normal mean is zero, but the variance is unknown; a treatment has no effect, whatever the baseline. The natural generalization: compare the best fit the null allows with the best fit overall. Lambda is the ratio of the two maximized likelihoods. It's at most one. Minus twice its log, W, is twice the log-likelihood lost by imposing the null. Large W means the null costs a lot of fit. For a Poisson rate, with Part 9's log-likelihood, W has this closed form. The simple-versus-simple Neyman–Pearson test compares the two likelihoods directly. This generalized full-model ratio follows that idea; in general it's a recipe, not a theorem, but an extraordinarily good one.
What's the null distribution of W? In 1938 Samuel Wilks proved that, in regular problems, if the null is true, W is approximately chi-squared, with degrees of freedom equal to the number of parameters the null pins down. The reason is Part 9's picture. Near its peak, the log-likelihood is a parabola with curvature n times the information. So twice the drop from the peak to the null value is the squared distance, measured in standard errors. And the MLE is approximately normal around the truth, so W is approximately a squared standard normal: chi-squared with one degree of freedom. One recipe, one reference distribution, for almost every test.
Check it by simulation. A hundred thousand Poisson samples of three, with the null true. W takes only a few values, because the total does, and the histogram is lumpy. Rejecting beyond three point eight four, the chi-squared five percent point, happens three point six percent of the time. With thirty observations, the histogram follows the chi-squared curve closely, and the size is five point four percent. Wilks' theorem is a large-sample result, like everything built on Part 9's asymptotics, and Part 22 shows how to correct it in small samples.
There are three classic ways to test with a likelihood, and they're three ways of reading one curve. Here is the horse-kick log-likelihood again, with the null hypothesis that the rate is point five per corps-year. The likelihood ratio test measures the vertical drop from the peak to the null value. Abraham Wald's test, from 1943, measures the horizontal distance from the MLE to the null, in standard errors. And C. R. Rao's score test, from 1948, measures the slope of the log-likelihood at the null value: under the null the score is centred at zero, and the test scales its observed departure by its null variance. The score test never needs the MLE at all, which makes it the cheapest of the three.
The numbers. The likelihood ratio statistic is four point five two, a p-value of point zero three four. Wald's is three point nine seven, point zero four six. The score statistic is four point eight four, point zero two eight. In large samples all three are chi-squared with one degree of freedom, and they agree to first order, as here. In small samples they can disagree, and the Wald test, which depends on how the parameter is written, can be poorly calibrated. None is uniformly best; Part 14 compares them on the Coverage Board. And Pearson's chi-squared, the subject of chapter eight, turns out to be a score test.
A last practical point: one tail or two? A one-sided test puts the whole five percent in one tail, so it rejects more readily in that direction, and never in the other. A two-sided test splits it, two and a half percent in each tail. A one-sided test is legitimate only if the direction was fixed before the data were seen. Picking the tail after looking, whichever way the data went, is really a two-sided test at ten percent. The likelihood ratio statistic is naturally two-sided; its signed square root gives the one-sided version.
What it does: Λ and W; Wilks (1938) by the quadratic approximation; simulation at n = 3 and 30; Wald, score and LR on the horse kicks; one- vs two-sided.; Numbers (computed): sizes 3.6%, 5.4%; H₀: λ = 0.5: W = 4.52 (p = 0.034), Wald 3.97 (0.046), score 4.84 (0.028)
7The everyday testsBachelor's4 min
The tests used every day are all built the same way. The z-test, when sigma is known: the distance from x-bar to the null value, in standard errors, compared with a standard normal. With sigma estimated, Student's t, with n minus one degrees of freedom. For paired data, the same test on the differences. For two independent groups, the pooled two-sample t, which assumes the groups share a variance. And Welch's version, which doesn't. Each is an estimate minus its null value, divided by its standard error, and Part 8 derived every one of the reference distributions. statkit's tests module writes each in a few lines.
The choice of test has to follow the design. Part 8's sleep data: ten patients, each given both drugs. Each line joins one patient's two results. Analysed as pairs, the differences give t equals four point oh six on nine degrees of freedom, and a p-value of point zero zero three. Analysed, wrongly, as two independent groups, the very same numbers give t of one point eight six and p of point zero eight. The difference of means is the same, one point five eight hours, but the patients differ a lot from each other, and pairing cancels that variation. Analyse the design you actually ran.
The pooled two-sample test assumes both groups have the same variance. What if they don't? That's the Behrens–Fisher problem, posed by Walter-Ulrich Behrens in 1929 and taken up by Fisher: for two normal means with unequal, unknown variances, the usual statistic has no exact t distribution independent of the unknown variance ratio. This is the classical Behrens–Fisher difficulty, not a claim that no valid exact or conservative procedure exists. Bernard Welch's practical answer, in 1947: use each group's own variance in the standard error, and approximate the null distribution by a t with fractional degrees of freedom, given by this formula, which Franklin Satterthwaite also found.
How much does it matter? Each row is twenty thousand pairs of normal samples with equal means, so every rejection is a false alarm, and a five percent test should reject five percent of the time. With equal sample sizes, the pooled test is only slightly off, six percent at worst. But give the first group ten observations and the second forty, and make the first group twice as spread out: the pooled test rejects eighteen percent of the time; four times as spread, twenty-nine percent. Reverse it, the large group being the variable one, and the pooled test almost never rejects, so the test is conservative here and can lose power against alternatives. Welch's test stays close to five percent in these rows. The pooled variance borrows the wrong group's spread whenever sizes and variances are unbalanced together.
The practical advice. Use Welch's test by default; when the variances really are equal, it loses almost nothing. Don't expect a permutation test to rescue you either: shuffling labels assumes the two groups are exchangeable under the null, which unequal variances violate. For paired designs, test the differences; for heavy tails, the rank tests of Part 16; for many groups, the analysis of variance of Part 13. And the Coverage Board will record Student against Welch at the end of chapter ten.
What it does: The catalogue; paired vs unpaired sleep data; Behrens–Fisher and Welch; a size grid; advice.; Numbers (computed): paired t = 4.06, p = 0.0028; unpaired p = 0.079; Student 18.4% / 29.4% at n = 10, 40
8Pearson's chi-squaredMaster's5 min
In 1900 Karl Pearson published the first general test of whether data fit a model: a criterion for deciding whether a set of deviations from what was expected could reasonably have arisen by chance. His example was Raphael Weldon's twenty-six thousand throws of twelve dice; a few years earlier he had argued, in the same spirit, that the roulette wheels of Monte Carlo were not random. Pearson got one thing wrong, the degrees of freedom when parameters have to be estimated from the data, and the young Fisher corrected him, a correction Pearson resisted bitterly.
Pearson's statistic compares each observed count with the count the model expects, squares the difference, and scales it by the expected count, which is roughly the count's variance. For independent multinomial trials with fixed categories and expected counts growing, the sum is approximately chi-squared with k minus one degrees of freedom: k counts, less one because they must add up to the total. And one more degree is lost per identifiable regular parameter fitted efficiently to the grouped counts, Fisher's correction. Arbitrary estimates or parameters fitted before binning need not yield this reference law. In the language of chapter six, Pearson's statistic is exactly the score test for a multinomial.
The most famous counts in biology. Gregor Mendel's peas, in 1866. Crossing plants and then crossing their offspring, his theory predicted round and wrinkled seeds in the ratio three to one. He counted five thousand four hundred and seventy-four round and one thousand eight hundred and fifty wrinkled. Pearson's statistic is point two six, and the p-value point six one: no evidence against three to one. Following two characters at once, shape and colour, the theory predicts nine to three to three to one. He counted three hundred and fifteen, a hundred and eight, a hundred and one, and thirty-two. The statistic is point four seven on three degrees of freedom, a p-value of point nine three. The observed bars sit almost exactly on the expected ones.
Is the chi-squared approximation good here? Simulate a hundred thousand harvests of five hundred and fifty-six plants in which the theory is exactly true, and compute Pearson's statistic for each. The chi-squared curve with three degrees of freedom fits the histogram, and rejecting beyond seven point eight one happens four point nine nine percent of the time. Now look at Mendel's value, point four seven, at the far left. Only seven percent of harvests where the theory is perfectly true fit as well as his did. That's not suspicious by itself. But Fisher looked at the left tail across all of Mendel's experiments.
In 1936 Fisher reanalysed all of Mendel's published experiments, and pooled the chi-squared statistics. The agreement with Mendel's ratios was so close that a fit at least that good would occur by chance less than once in ten thousand repetitions. This was a significance test in the other tail: the data were too good to be true. Fisher, who admired Mendel, suggested an assistant who knew what was expected may have shaded the counts. Historians and statisticians are still arguing about it. The idea, though, is now a standard forensic tool: real data are noisy, and data with too little noise deserve a second look.
Pearson's statistic also tests independence in a table. Two hundred patients from the World's clinic, classified by whether they were treated and whether they recovered. Fifty-seven percent of the treated recovered, against seventy-seven percent of the untreated. If treatment and recovery were independent, each cell would be expected to hold its row total times its column total over n: the grey numbers. Pearson's statistic is nine point three on one degree of freedom, p equals point zero zero two, and Fisher's exact test agrees. Strong evidence that treatment and recovery are associated. But associated how?
The World knows, because we built it: doctors treat the sicker patients, as in Part 5's Simpson's paradox. Among mild cases, the treated recover more often than the untreated; among severe cases, too. Within each severity the treatment helps. The test detected a real association, but the association runs through severity, and its sign is the opposite of the treatment's effect. A significance test answers the question, is there an association? It never answers why. That question belongs to Parts 35 to 37.
What it does: Pearson (1900); the statistic and its df; Mendel's 3:1 and 9:3:3:1; the null by simulation; Fisher (1936); independence in the clinic, and why it is confounded.; Numbers (computed): X² = 0.263 (p = 0.61), 0.47 (p = 0.93); clinic X² = 9.32, p = 0.0023
9Power and sample sizePractice4 min
Power isn't one number; it's a curve. For the two-sided z-test, here's the chance of rejecting as a function of the true effect, for ten observations. At zero effect, the curve touches five percent: there, the power is just the false-alarm rate. Far from zero, it climbs toward one. With thirty observations the valley narrows, and with a hundred it narrows again. A test is a detector, and this is its sensitivity curve: small effects need large samples to see.
Planning a study means turning that around. For a one-sample z-test at five percent, eighty percent power against an effect of point two standard deviations, which the psychologist Jacob Cohen called small, needs a hundred and ninety-seven observations. A medium effect, half a standard deviation, needs thirty-two. A large one, point eight, needs thirteen. The sample size grows like one over the effect squared: halve the effect and you need four times the data. A power analysis needs an effect size chosen before the data are seen, ideally the smallest effect that would matter. Cohen's book on power analysis made this standard practice, at least on paper.
In 1962 Cohen surveyed a year of papers in a leading psychology journal and estimated that the typical study had only about an even chance of detecting an effect of medium size. When Peter Sedlmeier and Gerd Gigerenzer repeated the survey a quarter of a century later, little had changed. You might think low power only means missing real effects. It does something worse: it distorts the effects that do get found.
Andrew Gelman and John Carlin made this vivid in 2014. Suppose the true effect is small, point one, and the study's standard error is point two, as with two groups of fifty. Here are four hundred replications of the study: each dot is one study's estimate. They scatter widely around the truth. A study is significant only if its estimate lands in a red zone, more than one point nine six standard errors from zero. That happens eight percent of the time. Now look at the studies that made it. To be significant, an estimate had to be at least point three nine, nearly four times the truth. On average, the significant estimates are almost five times too big. Gelman and Carlin call this a type M error, for magnitude. And nearly one in ten of them is significant in the wrong direction: a type S error, for sign. If only significant results get published, the published record is exaggerated, and sometimes backwards.
How bad it is depends on the power. At eight percent power, significant estimates are nearly five times too large. At thirty-two percent, about one and three quarter times. At eighty-one percent, only twelve percent too large, and the wrong sign essentially never. A well-powered study isn't just more likely to find an effect; selection exaggeration is much smaller in this model. Power alone does not remove confounding, measurement bias or model error.
Economists call it the winner's curse. If you filter noisy estimates by whether they're significant, you select the lucky ones. So when the studies are repeated, the effects shrink: the large replication project in psychology published in 2015 found effects about half the size of the originals, on average. The remedies are adequate power, deciding the analysis in advance, reporting estimates with honest intervals, the subject of Part 11, and the shrinkage estimators of Part 25, which can reduce exaggeration under an appropriate hierarchical model; selection still needs to be accounted for.
What it does: Power curves; n for 80%; Cohen (1962); type S and M; the winner's curse.; Numbers (computed): n = 197, 32, 13; at 8% power: 4.8× exaggeration, 8.7% wrong sign
10The peeking problemPractice4 min
Here's a habit that seems harmless. An experimenter collects data one observation at a time, and after every new observation, from the tenth on, runs a t-test. The red lines are the five percent critical values. Each wandering line is the t statistic of one experiment as the data accumulate, and in every one of them the null is true: the data are pure noise. But the paths wander, and some of them touch a red line. If the experimenter stops at the first crossing and reports p less than point zero five, every one of these is a false alarm. Each individual test had a five percent error rate. The procedure doesn't.
How bad is it? Simulate ten thousand experiments under the null, each peeking after every observation, and count how often p ever dips below point zero five. Willing to go to twenty observations, the false-positive rate is thirteen percent. To fifty, twenty-two. To a hundred, twenty-nine. To five hundred, forty-two percent. Peeking less often helps only a little: looking every tenth observation, up to a hundred, still gives twenty percent. And the curve never levels off. By the law of the iterated logarithm, a random walk eventually crosses any boundary that grows like root n, so a patient enough experimenter is certain to reach significance under a true null. Statisticians call it sampling to a foregone conclusion.
The problem has solutions, and they're old. During the war, Abraham Wald invented the sequential probability ratio test, designed from the start to be checked after every observation, with boundaries that account for it. In 1969 Peter Armitage and his colleagues computed the damage done by naive repeated testing, in a paper whose lessons medical trials took to heart. Clinical trials now use group-sequential designs, with a few planned looks at the data and stricter boundaries at each, from Stuart Pocock and from Peter O'Brien and Thomas Fleming. And the newest answer, anytime-valid inference, gives p-values and intervals you may check as often as you like. That's Part 58.
Time to add Part 10's promises to the Coverage Board. For a test, the board records its size: how often it rejects a true null, which should be five percent. Student's pooled t on two samples of ten men's heights: five point oh four percent. Kept. The same test when the group of ten is nearly three times as spread out as the group of forty: twenty-three point six percent. Broken. Welch's test in the same setting: five point one five. Kept. A t-test peeked at after every observation from ten to a hundred: twenty-nine percent. Badly broken. These World-height tests are approximate individually; the earlier normal-data simulation shows the same failure even when every fixed-sample test is exact. And a permutation test on samples of eight of the World's skewed incomes: four point eight five percent. Kept, under exchangeability, with the plus-one Monte Carlo p-value correction and no parametric shape assumption. Five rows, two of them broken by habits rather than by mathematics.
What it does: Running t paths; the false-positive rate against the patience; Wald's SPRT, Armitage et al., group-sequential designs; the Board's Part 10 rows.; Numbers (computed): 13% (n ≤ 20), 22% (50), 29% (100), 42% (500); every 10th up to 100: 20%
11What p-values are notBachelor's5 min
The most common misreading first. A p-value is a probability about the data, computed assuming the null is true. It is not the probability that the null is true, given the data. Confusing the two is the transposed conditional, the same mistake as Part 2's screening test, where a positive result from an accurate test still usually meant no disease. The chance that a significant result is a false alarm comes from Bayes' rule, and it depends on something the p-value knows nothing about: what fraction of the hypotheses being tested were true to begin with.
Here it is in pictures. A thousand hypotheses are tested, in some field where one in ten is a real effect: the green squares. With eighty percent power, eighty real effects are significant in expectation. The picture fixes the expected counts for illustration. With a five percent false-alarm rate, forty-five of the nine hundred nulls are significant in expectation. So of the hundred and twenty-five significant results, forty-five, thirty-six percent, are false, even though every test was performed perfectly at the five percent level. If only one hypothesis in a hundred is real, the false share rises to eighty-six percent. John Ioannidis built a famous argument on exactly this arithmetic in 2005.
Second misreading: that a p-value is a stable property of a phenomenon. Run the same experiment twenty-five times: a true effect of half a standard deviation, thirty-two subjects per group. Each row is one run, with its estimate, its ninety-five percent interval, and its p-value. The power is about fifty percent, so about half the runs are significant, and half aren't, by chance alone. The p-values jump from point zero zero one to point six. Across many runs, the middle eighty percent of p-values stretch from about point zero zero one to point four six. Geoff Cumming called it the dance of the p-values. The intervals dance too, but they show you how much: every one of them is wide, and that width is the honest message.
Third: a small p-value doesn't mean a large effect. With a million people per group, a difference of five thousandths of a standard deviation gives z of three point five and a p-value of about four in ten thousand. In heights, that's a difference of about a third of a millimetre: highly significant, and utterly unimportant. The p-value mixes the size of the effect with the size of the sample. Fourth: a large p-value doesn't mean no effect. Absence of evidence isn't evidence of absence. With six cups, the tea test cannot go below point zero five, however skilled the lady: its smallest possible p-value is exactly one in twenty.
Fifth, and subtler: a significant result and a non-significant result need not differ significantly from one another. Study A estimates an effect of twenty-five, plus or minus ten: p equals point zero one two. Study B estimates ten, plus or minus ten: p equals point three two. It's tempting to say A found an effect and B didn't, so they disagree. But the difference between them is fifteen, assuming independent studies, with a standard error of fourteen: z of about one, p of point two nine. No evidence that they differ at all. Andrew Gelman and Hal Stern made the point in 2006. And sixth: a p-value depends not only on the data but on the stopping rule and on how many analyses were tried, as chapters ten and twelve show.
In 2016 the American Statistical Association issued, for the first time in its history, a formal statement on a matter of statistical practice: on p-values. It has six principles. P-values can indicate how incompatible the data are with a specified model. They don't measure the probability that the hypothesis is true, or that the data were produced by chance alone. Decisions shouldn't rest only on whether a p-value passes a threshold. Proper inference requires full reporting and transparency. A p-value doesn't measure the size of an effect or its importance. And by itself, a p-value isn't a good measure of evidence. Every principle on this list is a chapter of this part.
What it does: p ≠ P(H₀ ∣ data) and 1,000 hypotheses; the dance of the p-values; significance ≠ size; absence of evidence; Gelman & Stern; the ASA's six principles.; Numbers (computed): 36% of significant results false (86% at 1 in 100 real)
12Many testsPractice4 min
Every test so far was a single test. Real studies run many. If you test m hypotheses that are all truly null, each at five percent, and independently, the chance that at least one comes out significant is one minus point nine five to the m. With five tests it's twenty-three percent. With twenty, sixty-four percent: more likely than not. With a hundred, it's a near certainty. Simulation agrees. The probability of at least one false alarm across the whole family is called the family-wise error rate, and a study measuring twenty outcomes, at five percent each, has a family-wise error rate of almost two in three.
Here are a hundred tests in which every null is true. By chapter three, their p-values are a hundred uniform random numbers, scattered across zero to one. Three of them happen to fall below point zero five. Report those three, and you have three discoveries, every one of them false. Move the line to point zero zero zero five, the five percent divided by a hundred, and none survive.
That's the Bonferroni correction, named for Carlo Bonferroni's inequality. The chance that any true-null p-value among m tested hypotheses falls below alpha over m is at most the sum of the individual chances, by the union bound of Part 2. Each of those is at most alpha over m, so the total is at most alpha, whatever the dependence between the tests. With twenty tests, the family-wise error rate drops from sixty-four percent to five. The price is power: each test now needs a z of three instead of two. Sture Holm's 1979 step-down version is at least as powerful with the same family-wise error control, and Yoav Benjamini and Yosef Hochberg's false discovery rate, in 1995, asks for less, controlling the expected false-discovery proportion rather than the chance of any. That's Part 33.
The most memorable demonstration came from neuroscience. In 2009, Craig Bennett and his colleagues put a dead Atlantic salmon in an MRI scanner, showed it photographs of people in social situations, and asked it to judge their emotions. Analysed without correcting for multiple comparisons, a small cluster of voxels in the salmon's brain lit up. A brain scan runs a separate test at every one of more than a hundred thousand voxels, and some will be significant by chance. With a correction, the dead fish's thoughts vanished. The poster won an Ig Nobel prize, and helped make multiple-comparison corrections standard in the field.
There's a quieter version of the problem that Andrew Gelman and Eric Loken called the garden of forking paths. The extra tests don't have to be run. If the choice of outcome, subgroup, covariates or exclusions is made after looking at the data, the analysis that gets reported is one of many that could have been, and the p-value is computed as if it were the only one. In 2011 Joseph Simmons, Leif Nelson and Uri Simonsohn showed that a few such innocent-looking choices can push the false-positive rate above fifty percent. The remedies are deciding the analysis in advance, correcting for every test actually considered, and the theory of inference after selection, Part 56.
What it does: 1 − 0.95ᵐ; 100 null p-values; Bonferroni by the union bound; the dead salmon; forking paths.; Numbers (computed): 0.64 at m = 20 → 5.0% with Bonferroni
Recap, problems, and the road aheadAll tracks3 min
Part ten in thirteen lines. Arbuthnot's eighty-two years and the lady's eight cups share Fisher's logic: a null hypothesis, a statistic, and the probability of something at least as extreme. When the experimenter randomized, the null distribution is the randomization itself, and the test is exact. Under an exact continuous null distribution, a p-value is uniform; discrete p-values are generally super-uniform. Neyman and Pearson added a second error and turned testing into optimization: the most powerful test fills a knapsack by likelihood ratio, and the likelihood ratio, with Wilks' theorem, gives a test for almost anything. The everyday tests are estimates over standard errors, and Welch's test survives unequal variances where Student's doesn't. Pearson's chi-squared tests counts, and showed Mendel's to be almost too good. Power decides whether a study can find an effect, and low power exaggerates the effects it does find. Peeking breaks a test's size; a p-value is not the probability that the null is true; and many tests need correcting.
Where it comes back. Every test inverts into a confidence interval, which is Part 11. Randomization inference returns with experiments and permutation methods in Parts 13, 16 and 35. The likelihood trinity runs logistic and Poisson regression in Parts 14 and 24. Sequential testing comes back with clinical trials and anytime-valid inference in Parts 35 and 58; multiple testing and the false discovery rate in Part 33; and the Bayesian answer to the question p-values can't answer, how probable is the hypothesis, in Part 15.
Six problems, with full solutions in the README. A ten-cup tea test; the uniform p-value proved; a most powerful test for a Poisson count; the likelihood ratio for a proportion, applied to Arbuthnot; a sample size for ninety percent power; and the family-wise error of ten tests, with Šidák's exact correction. Pause here if you want to try them.
The books and papers this part follows: Casella and Berger, Lehmann and Romano's Testing Statistical Hypotheses, Fisher's own two books, and David Salsburg's history, The Lady Tasting Tea, with the original papers from Arbuthnot to the American Statistical Association.
Ten parts of sixty-five. We can ask whether a pattern is too strong to be chance, and we know the many ways the answer can mislead. But a test says yes or no. How big is the effect, and how sure are we of its size? The interval taught in every textbook for a proportion fails, in a sawtooth pattern, even with large samples. Part 11: honest intervals.
Where it goes next. Tests are inverted into confidence intervals in Part 11 and again in Part 46; permutation inference returns in Parts 13, 16 and 35; the likelihood ratio, Wald and score tests in Parts 14, 22 and 24; power and design in Parts 13 and 35; sequential and anytime-valid testing in Parts 35 and 58; multiple testing and the false discovery rate in Parts 33 and 56.
Key results
The part's results in one place, for revision.
Try it
Lab 10 · What a 5% test promises, and two ways to break it
Run 20,000 one-sample t-tests (n = 15) under the null and under two alternatives and compare the share of p-values below 0.05 with the exact power; then measure the size of Student's and Welch's two-sample tests when the spreads differ, and of a t-test that is checked after every observation.
python -m videos.stats.labs 10
needs numpy, scipy, matplotlib · download lab10.py ·
source on GitHubP(p < 0.05), true mean 0.0 sd 0.050 (exact 0.050)
P(p < 0.05), true mean 0.3 sd 0.193 (exact 0.192)
P(p < 0.05), true mean 0.8 sd 0.819 (exact 0.821)
null p-values: largest gap from the uniform CDF 0.0053 (noise level about 0.0096)
two-sample size, unequal spreads Student 0.244 (variance-ratio approximation 0.227) Welch 0.054
one look at n = 100 0.054 (promise 0.050)
ever significant, peeking up to n = 20, 50, 100, 500 0.128 0.217 0.281 0.413 (the film: 0.13, 0.22, 0.29, 0.42)
A single test at a fixed n keeps its 5%, and its power is what the noncentral t says. Pool unequal variances or stop at the first p < 0.05 and the same nominal 5% becomes 20% to 40%.
The code (91 lines; it asserts its own result)
"""Lab 10: check a test's size and power against theory, then break the size by pooling and by peeking."""
import numpy as np
from scipy import stats
from videos.coursekit import labs
from explainer.stats.kit import tests as skt
TITLE = "What a 5% test promises, and two ways to break it"
GOAL = ("Run 20,000 one-sample t-tests (n = 15) under the null and under two alternatives and compare the share of "
"p-values below 0.05 with the exact power; then measure the size of Student's and Welch's two-sample tests "
"when the spreads differ, and of a t-test that is checked after every observation.")
TASKS = [
"Look only after every 10th observation up to 100. How much of the inflation goes away?",
"Swap the group sizes in the two-sample study (40 with the large spread, 10 with the small). Which way does "
"Student's size move now, and why?",
"Replace the normal data in the first study by exponentials minus 1 (mean 0). Is the p-value still uniform at "
"n = 15? At n = 200?",
]
def run(seed=0):
rng = np.random.default_rng(seed)
lab = labs.Lab()
# 1. The p-value: uniform under the null, and piled near zero with the power the noncentral t predicts.
n, reps = 15, 20_000
crit = stats.t.ppf(0.975, n - 1)
pvals = {}
for delta in (0.0, 0.3, 0.8):
x = rng.normal(delta, 1, (reps, n))
t = x.mean(1) / (x.std(1, ddof=1) / np.sqrt(n))
p = 2 * stats.t.sf(np.abs(t), n - 1)
assert abs(skt.t_test(x[0])["p"] - p[0]) < 1e-12, "the vectorized test is statkit's t_test"
nc = delta * np.sqrt(n)
power = stats.nct.sf(crit, n - 1, nc) + stats.nct.cdf(-crit, n - 1, nc) if delta else 0.05
share = np.mean(p < 0.05)
pvals[delta] = p
lab.row(f"P(p < 0.05), true mean {delta} sd", f"{share:.3f} (exact {power:.3f})")
assert abs(share - power) < 4 * np.sqrt(power * (1 - power) / reps), "rejection rate matches the exact power"
ks = stats.kstest(pvals[0.0], "uniform").statistic
lab.row("null p-values: largest gap from the uniform CDF", f"{ks:.4f} (noise level about {1.36 / np.sqrt(reps):.4f})")
assert ks < 0.015, "under the null the p-value is uniform"
# 2. Student against Welch when 10 observations have 2.7 times the spread of the other 40 (no true difference).
R2 = 4000
a, b = rng.normal(0, 2.7, (R2, 10)), rng.normal(0, 1, (R2, 40))
size_student = np.mean([skt.t_test(u, v)["p"] < 0.05 for u, v in zip(a, b)])
size_welch = np.mean([skt.welch_test(u, v)["p"] < 0.05 for u, v in zip(a, b)])
# what the pooled variance does: the statistic's true variance over the variance the pooled formula assumes
ratio = (2.7 ** 2 / 10 + 1 / 40) / ((9 * 2.7 ** 2 + 39) / 48 * (1 / 10 + 1 / 40))
approx = 2 * stats.norm.sf(stats.t.ppf(0.975, 48) / np.sqrt(ratio))
lab.row("two-sample size, unequal spreads", f"Student {size_student:.3f} (variance-ratio approximation {approx:.3f}) Welch {size_welch:.3f}")
assert abs(size_student - approx) < 0.04 and size_student > 0.15, "the pooled test's 5% is really over 20%"
assert abs(size_welch - 0.05) < 0.02, "Welch keeps the size"
# 3. Peeking: a t-test after every observation from the 10th on, null true.
R3, N = 5000, 500
z = rng.standard_normal((R3, N))
m = np.arange(1, N + 1)
cs, cs2 = np.cumsum(z, 1), np.cumsum(z * z, 1)
with np.errstate(divide="ignore", invalid="ignore"):
tpath = (cs / m) / np.sqrt((cs2 - cs ** 2 / m) / (m - 1) / m)
single = np.abs(tpath) > stats.t.ppf(0.975, np.maximum(m - 1, 1)) # the test at each n, taken on its own
hit = single.copy()
hit[:, :9] = False # the first look is at the 10th observation
ever = np.maximum.accumulate(hit, axis=1).mean(0) # ever[n - 1]: rejected at some look up to n
film = {20: 0.13, 50: 0.22, 100: 0.29, 500: 0.42}
lab.row("one look at n = 100", f"{hit[:, 99].mean():.3f} (promise 0.050)")
lab.row("ever significant, peeking up to n = 20, 50, 100, 500",
" ".join(f"{ever[e - 1]:.3f}" for e in film) + " (the film: 0.13, 0.22, 0.29, 0.42)")
assert abs(hit[:, 99].mean() - 0.05) < 0.015, "each single test keeps its 5%"
assert all(abs(ever[e - 1] - v) < 0.03 for e, v in film.items()), "the procedure does not: the film's rates"
lab.note = ("A single test at a fixed n keeps its 5%, and its power is what the noncentral t says. Pool unequal "
"variances or stop at the first p < 0.05 and the same nominal 5% becomes 20% to 40%.")
fig, ax = labs.figure(2, size=(11, 4.2))
bins = np.linspace(0, 1, 21)
for delta, color in ((0.0, labs.BLUE), (0.3, labs.GOLD), (0.8, labs.RED)):
ax[0].hist(pvals[delta], bins=bins, density=True, histtype="step", lw=1.8, color=color, label=f"true mean {delta} sd")
ax[0].set(title="20,000 p-values of a t-test, n = 15", xlabel="p-value", ylabel="density", yscale="log")
ax[0].legend()
ax[1].plot(m[9:], ever[9:], color=labs.RED, label="ever p < 0.05, looking after every observation")
looks = np.array([10, 14, 20, 30, 50, 70, 100, 140, 200, 300, 500])
ax[1].plot(looks, single[:, looks - 1].mean(0), "s-", color=labs.BLUE, lw=1.2, ms=4, label="one test at n, no peeking")
ax[1].plot(list(film), list(film.values()), "o", color=labs.GOLD, label="the film's rates")
ax[1].axhline(0.05, color=labs.MUTED, ls="--", lw=1)
ax[1].set(title="False-positive rate of a t-test with a true null", xlabel="largest sample size n", ylabel="rate", xscale="log")
ax[1].legend()
lab.fig = fig
return lab
Now change it
- Look only after every 10th observation up to 100. How much of the inflation goes away?
- Swap the group sizes in the two-sample study (40 with the large spread, 10 with the small). Which way does Student's size move now, and why?
- Replace the normal data in the first study by exponentials minus 1 (mean 0). Is the p-value still uniform at n = 15? At n = 200?
Problems, with solutions
Try each problem before opening its solution.
1. Ten cups. The tea with 10 cups, five milk-first: what is \(p\) if she gets four of the five right? What is the smallest possible \(p\)?
Solution
With five of each, P(j right) = C(5, j)C(5, 5 − j)/C(10, 5) = C(5, j)²/252.
- Four right: P(≥ 4) = (25 + 1)/252 = 0.103. Not significant: four of five is easy to reach by guessing.
- The smallest possible p is 1/252 = 0.0040, for a perfect score.
2. The uniform p-value. Show that if \(T\) has a continuous distribution under \(H_0\), then \(p = 1 - F_0(T)\) is Uniform\((0,1)\).
Solution
P(p ≤ u) = P(1 − F₀(T) ≤ u) = P(F₀(T) ≥ 1 − u). For continuous F₀, F₀(T) is Uniform(0, 1) (the probability integral transform: P(F₀(T) ≤ v) = P(T ≤ F₀⁻¹(v)) = v). So P(p ≤ u) = u.
3. A most powerful Poisson test. \(X \sim\) Poisson\((\lambda)\), one observation: find the most powerful test of \(\lambda = 1\) against \(\lambda = 3\) of size at most \(0.05\), and its power. (Randomize if you want size exactly \(0.05\).)
Solution
p₃(x)/p₁(x) = 3ˣe⁻², which increases in x, so the NP test rejects for large x.
- P₁(X ≥ 4) = 0.0190 and P₁(X ≥ 3) = 0.0803, so the best non-randomized test of size at most 0.05 rejects for X ≥ 4. It has size 0.019 and power P₃(X ≥ 4) = 0.353.
- For size exactly 0.05, also reject at X = 3 with probability γ = (0.05 − 0.0190)/P₁(X = 3) = 0.506. The power rises to 0.353 + 0.506 · 0.224 = 0.466.
4. The LRT for a proportion. Derive \(W = -2\log\Lambda\) for \(H_0: p = p_0\) from \(x\) successes in \(n\) trials, and evaluate it for Arbuthnot's 82 of 82 with \(p_0 = \tfrac12\).
Solution
W = 2[x log(x/(np₀)) + (n − x) log((n − x)/(n(1 − p₀)))], taking 0 log 0 = 0. For x = n = 82 and p₀ = ½, W = 2 · 82 log 2 = 113.7. The χ²₁ tail is 1.5 × 10⁻²⁶. That is the same order as the exact two-sided sign test, 2 · 2⁻⁸² = 4.1 × 10⁻²⁵; Wilks' approximation is poor this far out in the tail.
5. Sample size. How many observations per group give 90% power to detect \(\delta = 0.4\sigma\) with a two-sided two-sample \(z\)-test at \(\alpha = 0.05\)?
Solution
For two groups of n, SE(x̄ − ȳ) = σ√(2/n). So n = 2((z₀.₉₇₅ + z₀.₉₀)σ/δ)² = 2(1.960 + 1.282)²/0.16 = 131.3: 132 per group.
6. Ten tests. Ten independent tests, all nulls true: find \(P(\text{at least one } p < 0.05)\), and the Šidák level \(1 - (1 - \alpha)^{1/m}\) that makes it exactly \(0.05\).
Solution
P(at least one) = 1 − 0.95¹⁰ = 0.401. Testing each at 1 − 0.95^(1/10) = 0.005116 makes it exactly 0.05 for independent tests (Šidák). That is barely larger than Bonferroni's 0.005.
Notes and sources
Where it comes back
| Idea | Returns in |
|---|---|
| tests inverted into intervals | 11, 46 |
| randomization and permutation inference | 13, 16, 35 |
| likelihood ratio, Wald and score tests | 14, 22, 24 |
| χ² tests for tables | 14 |
| power, design, sample size | 13, 35 |
| sequential and anytime-valid testing | 35, 58 |
| multiple testing, FDR, selection | 33, 56 |
| posterior probabilities of hypotheses | 15, 26 |
| the Coverage Board | every part; 65 |
Sources
- The founding papers.
- J. Arbuthnot, Phil. Trans. 27 (1710).
- K. Pearson, Phil. Mag. 50 (1900).
- R. A. Fisher, Statistical Methods for Research Workers (1925); The Design of Experiments (1935); "Has Mendel's work been rediscovered?", Ann. Sci. 1 (1936); Statistical Methods and Scientific Inference (1956).
- J. Neyman & E. S. Pearson, Biometrika 20A (1928); Phil. Trans. A 231 (1933).
- S. S. Wilks, Ann. Math. Stat. 9 (1938).
- A. Wald, Trans. AMS 54 (1943); Ann. Math. Stat. 16 (1945).
- C. R. Rao, Proc. Camb. Phil. Soc. 44 (1948).
- B. L. Welch, Biometrika 34 (1947).
- Tests and designs.
- S. Karlin & H. Rubin, Ann. Math. Stat. 27 (1956).
- P. Armitage, C. McPherson & B. Rowe, JRSS A 132 (1969).
- S. Pocock, Biometrika 64 (1977); P. O'Brien & T. Fleming, Biometrics 35 (1979).
- S. Holm, Scand. J. Stat. 6 (1979); Y. Benjamini & Y. Hochberg, JRSS B 57 (1995).
- Misuse and repair.
- J. Cohen, J. Abnorm. Soc. Psych. 65 (1962); P. Sedlmeier & G. Gigerenzer, Psych. Bull. 105 (1989).
- J. Ioannidis, PLoS Med. 2 (2005); A. Gelman & H. Stern, Am. Stat. 60 (2006).
- G. Cumming, Persp. Psych. Sci. 3 (2008); J. Simmons, L. Nelson & U. Simonsohn, Psych. Sci. 22 (2011).
- A. Gelman & J. Carlin, Persp. Psych. Sci. 9 (2014); Open Science Collaboration, Science 349 (2015).
- R. Wasserstein & N. Lazar, Am. Stat. 70 (2016); S. Greenland, Am. Stat. 73 (2019).
- C. Bennett et al., J. Serendipitous Unexpected Results 1 (2010; poster 2009).
- A. Franklin et al., Ending the Mendel–Fisher Controversy (2008).
- Textbooks and history.
- G. Casella & R. Berger, Statistical Inference (2nd ed., 2002), ch. 8.
- E. Lehmann & J. Romano, Testing Statistical Hypotheses (4th ed., 2022).
- D. Salsburg, The Lady Tasting Tea (2001); S. Stigler, The History of Statistics (1986).
About this partfrom its README
Part 10 of a sixty-five-part course in statistics, from a first course to a PhD (see the series plan and the syllabus), and the last part of Stage I, Bachelor's: Foundations. Parts 8 and 9 built estimators and their sampling distributions. This part asks when a pattern is too strong to be chance.
It opens with two stories. In 1710 John Arbuthnot found more boys than girls christened in London in each of 82 years: (1/2)⁸² ≈ 2.1 × 10⁻²⁵. Then there is Fisher's lady tasting tea (1935): with eight cups, a perfect score by guessing has probability 1/70. From there the part covers:
- Fisher's logic, and which null was really rejected (an illustrative independent equal-year model with male probability 51.6% makes 82 straight wins about a 98% event; Nicolaus Bernoulli, 1713);
- exact randomization or exchangeability calculations: the tea, Fisher's exact test, and Darwin's Zea mays sign flips (863 of 32,768);
- the p-value, uniform for an exact continuous null and super-uniform for discrete nulls, and its distribution under alternatives;
- Neyman and Pearson's two errors and the Neyman–Pearson lemma, as a knapsack over all 2,048 rejection regions of a dice problem;
- the likelihood ratio test, Wilks' theorem, and the Wald, score and LR trinity;
- the everyday tests, and Student vs Welch;
- Pearson's χ², Mendel's peas and Fisher's "too good to be true", and a χ² association in the World's clinic that is confounded;
- power, sample size and Gelman & Carlin's type S and M errors;
- the peeking problem;
- what p-values are not, ending with the ASA statement (2016);
- many tests and Bonferroni.
Every number on screen is computed in compute.py. The Museum supplies:
- Arbuthnot's christenings (
museum.ARB_*); - Darwin's maize (
museum.DARWIN_ZEA); - Mendel's counts (
museum.MENDEL_*); - Student's sleep data (
museum.SLEEP_*).
Heights, incomes and the clinic come from the World (seed 1662). Everything else is a seeded simulation or exact.
Built in this part:
- The permutation machine (
PermutationMachineinexplainer/stats/viz.py): tokens dealt into two rows, the shuffled statistic stacking into the null distribution. statkit.tests(explainer/stats/kit/tests.py): z, t, paired, Welch, permutation (exact or Monte Carlo), Fisher's sign flips, the sign test, Fisher's exact test, Pearson's χ², the LRT, Bonferroni, power and sample size. Every one is checked against SciPy intests/test_stats_kit_tests.py, which also reproduces Fisher's 863/32,768.
The Coverage Board gains five rows. Size rows carry nominal 5%, with R = 10,000 replications; the permutation row has 2,000. Its Monte Carlo p-values include the observed assignment with the plus-one correction. The Darwin sign-flip calculation requires sign exchangeability; a design-based interpretation additionally requires documented random assignment and a sharp null. Equal regional means alone do not establish the two-sample permutation null.
| Method | Setting | Achieved size | Verdict |
|---|---|---|---|
| Student's two-sample t | men's heights, n = 10, 10 | 5.04% | kept |
| Student's two-sample t | σ₁ ≈ 2.7σ₂, n = 10, 40 | 23.63% | broken |
| Welch's t | σ₁ ≈ 2.7σ₂, n = 10, 40 | 5.15% | kept |
| t-test, peeking after every observation | men's heights, n = 10 … 100 | 29.11% | broken |
| permutation test | incomes, n = 8, 8 | 4.85% | kept |
Chapter notes
| # | Chapter | What it does | Numbers (computed) |
|---|---|---|---|
| 0 | More boys than girls, and a cup of tea | Arbuthnot's paper and his 82 years plotted; the tea; objectives. | male share 0.503–0.536; 484,382 boys, 453,841 girls; p = 2.07 × 10⁻²⁵; 1/70 |
| 1 | Fisher's logic | Null, statistic, p; the sign test; Fisher's disjunction; which null was rejected; 's Gravesande and Bernoulli; where 5% came from. | P(T ≥ 15 of 20) = 0.0207; per-year win 0.99975, all 82: 0.98 |
| 2 | Exact tests by design | The tea's hypergeometric null; designs of 6–12 cups and the power of an imperfect taster; Fisher's exact test; Darwin's 15 pairs and all 2¹⁵ sign flips; the permutation machine on the World; randomization as the source of validity. | 1, 16, 36, 16, 1 /70; perfect-score power 0.11, 0.25, 0.51 at q = 0.7, 0.8, 0.9; Darwin p = 0.0263 / 0.0527 (t: 0.0497); regions p = 1,916/3,432 = 0.558 |
| 3 | The p-value | Definition; uniform under H₀ (proof); 20,000 t-tests at δ = 0, 0.3, 0.8; discrete super-uniform p; surprise in bits. | P(p < 0.05) = 0.049, 0.194, 0.819 |
| 4 | Two kinds of error | Neyman & Pearson (1928, 1933); the decision table; sliding the cut; power against n; the two philosophies. | n = 32 (80%), 43 (90%) for δ = 0.5σ |
| 5 | The Neyman–Pearson lemma | Statement; two dice, one loaded; the knapsack; all 2,048 regions and the frontier; the proof; UMP one-sided tests. | best size-1/6 region {10, 11, 12}: power 0.233 |
| 6 | The likelihood ratio test | Λ and W; Wilks (1938) by the quadratic approximation; simulation at n = 3 and 30; Wald, score and LR on the horse kicks; one- vs two-sided. | sizes 3.6%, 5.4%; H₀: λ = 0.5: W = 4.52 (p = 0.034), Wald 3.97 (0.046), score 4.84 (0.028) |
| 7 | The everyday tests | The catalogue; paired vs unpaired sleep data; Behrens–Fisher and Welch; a size grid; advice. | paired t = 4.06, p = 0.0028; unpaired p = 0.079; Student 18.4% / 29.4% at n = 10, 40 |
| 8 | Pearson's χ² | Pearson (1900); the statistic and its df; Mendel's 3:1 and 9:3:3:1; the null by simulation; Fisher (1936); independence in the clinic, and why it is confounded. | X² = 0.263 (p = 0.61), 0.47 (p = 0.93); clinic X² = 9.32, p = 0.0023 |
| 9 | Power and sample size | Power curves; n for 80%; Cohen (1962); type S and M; the winner's curse. | n = 197, 32, 13; at 8% power: 4.8× exaggeration, 8.7% wrong sign |
| 10 | The peeking problem | Running t paths; the false-positive rate against the patience; Wald's SPRT, Armitage et al., group-sequential designs; the Board's Part 10 rows. | 13% (n ≤ 20), 22% (50), 29% (100), 42% (500); every 10th up to 100: 20% |
| 11 | What p-values are not | p ≠ P(H₀ ∣ data) and 1,000 hypotheses; the dance of the p-values; significance ≠ size; absence of evidence; Gelman & Stern; the ASA's six principles. | 36% of significant results false (86% at 1 in 100 real) |
| 12 | Many tests | 1 − 0.95ᵐ; 100 null p-values; Bonferroni by the union bound; the dead salmon; forking paths. | 0.64 at m = 20 → 5.0% with Bonferroni |
| 13 | Outro | Recap, payoffs, problems, references, the Transcript, Part 11's question. | — |
The syllabus's plan for this partfrom SYLLABUS.md, the plan of record
- Hook: Arbuthnot (1710) and the lady tasting tea (Fisher 1935). (1/2)⁸² ≈ 2.1 × 10⁻²⁵; 1/70.
- Fisher's logic. Null, statistic, tail probability; Arbuthnot's sign test.
- Exact tests by design. The tea's hypergeometric null; Fisher's exact test; randomization as the source of validity.
- p-values. Uniform under H₀ (proved); their distribution under alternatives.
- Neyman–Pearson (1933). Two errors, size and power.
- The Neyman–Pearson lemma for simple hypotheses, proved as a knapsack (Part 46 generalizes).
- The likelihood ratio test. Wilks' theorem, stated; one-sided vs two-sided.
- The everyday tests. z, one- and two-sample t, paired t; Student vs Welch (1947).
- Pearson's χ² (1900). Goodness of fit and independence; Mendel and Fisher's "too good to be true" (1936).
- Power and sample size. n for 80% power; type M and S errors (Gelman & Carlin 2014).
- The peeking problem. Checking after every observation: the false-positive rate climbs (computed). Sequential methods come in Parts 35 and 58.
- What p-values are not. p ≠ P(H₀ | data); the dance of the p-values; the ASA statement (2016).
- Many tests, first look. Bonferroni; the dead-salmon problem (Part 33).
- Outro.
Built: the permutation machine; statkit.tests. Data: Arbuthnot; Mendel.
Build the film
python -m videos.stats.stats10.compute # the part's numbers, into .cache/stats10
python tools/build.py stats10 # render and assemble the film
EXPLAINER_TTS=silent python tools/qa_scene.py stats10 Hook # one chapter, silent, with a contact sheet
Scenes: videos/stats/stats10. Setup: see the course page. Source of these notes: the README and the scenes' narration.
Build it
python -m videos.stats.stats10.compute # once: every computed item (about 20 s; cached in .cache/stats10)
python tools/build.py stats10 -q l # fast 480p preview
python tools/build.py stats10 # 1080p30 -> renders/stats10.mp4
python tools/qa_scene.py stats10 Lemma # one chapter, silent, with a contact sheet
python tools/lecture_length.py stats10 --floor 50