Stage II · Bachelor's: Methods
Part 13 of 65Experiments by Design
How should data be collected so that the answer is unambiguous?
In 1919 Fisher arrives at Rothamsted to analyse seventy-six years of Broadbalk wheat records, which can describe what happened but cannot isolate what a manure does. A simulated uniformity trial shows why: identically treated plots differ by about 8% of the mean, in patches, with a drift from west to east. On the field-trial simulator a tidy systematic layout is badly biased, randomization makes the estimate unbiased and supplies its own test, replication shrinks the error, and blocking removes the gradient from it. One-way ANOVA is Pythagoras, SST = SSB + SSW; contrasts and Tukey's HSD handle many comparisons; Latin squares, factorials, fractions of them and response surfaces on the island bakery spend runs carefully. The part turns on the split plot, where using the wrong error stratum rejects a true null 25.6% of the time, and ends with power, the minimum detectable effect, and the same principles in online A/B tests with CUPED and the sample-ratio check.
What you need. Calculus and the matrix language of Part 4; no agronomy is assumed.
- Hook
- Fisher at Rothamsted, 1919
- Mathematics
- randomization, ANOVA geometry, blocking, factorials, fractional factorials, response surfaces, A/B tests
- Built
- a field-trial simulator
What you will be able to do
Bachelor's
- Explain what replication, randomization and blocking each buy, and lay out a randomized complete block design.
- Carry out a randomization test and a one-way ANOVA, and read the F table.
Master's
- Derive SST = SSB + SSW as a projection, and compute 2^k effects by Yates's algorithm.
- Work out the aliases and resolution of a fractional factorial from its defining relation.
- Analyse a split plot with the correct error stratum for each factor.
PhD
- State the Kiefer-Wolfowitz equivalence theorem for approximate designs and verify it for quadratic regression on [-1, 1].
- State exactly what a randomization test assumes (a sharp null, the actual assignment mechanism) against what the normal-theory F test assumes.
Practice
- Plan a sample size from a minimum detectable effect, and explain why a significant result from an underpowered study exaggerates.
- Run an A/B test with CUPED adjustment and a sample-ratio check before reading the result.
Contents
Each chapter has a home level. Choose a track to see what to read and watch: Bachelor's 36 min · Master's 75 min · PhD 81 min · Practice 48 min.
- 0Rothamsted, 1919Bachelor's3 min
- 1Three principlesBachelor's5 min
- 2Randomization as inferenceBachelor's5 min
- 3One-way ANOVABachelor's6 min
- 4Contrasts and many comparisonsMaster's6 min
- 5BlockingBachelor's6 min
- 6Latin squares and crossoversMaster's5 min
- 7FactorialsBachelor's7 min
- 8Fractional factorialsMaster's6 min
- 9Response surfacesMaster's5 min
- 10Split plotsMaster's5 min
- 11Optimal designPhD6 min
- 12Power and sample sizePractice5 min
- 13Online experimentsPractice7 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.
Rothamsted, 1919Bachelor's3 min
In 1843 John Bennet Lawes, who had made a fortune from artificial fertilizer, and the chemist Joseph Henry Gilbert began an experiment on a field called Broadbalk, at Rothamsted, north of London. They sowed winter wheat, divided the field into long strips, and gave each strip a different manure: none at all, farmyard manure, nitrogen, phosphate, potash, and their combinations. Every year they harvested each strip and weighed the grain. The experiment is still running today, one of the oldest continuous field experiments in the world. By 1919 there were seventy-six years of carefully kept numbers.
In 1919 the director, John Russell, hired a twenty-nine-year-old mathematician, Ronald Fisher, to see what statistics could make of the records. Fisher's first papers, Studies in Crop Variation, analysed the Broadbalk yields from 1852 onward. He found slow trends, cycles and the effects of rainfall. But every comparison was tangled: a strip that did well might have had the better soil, the drier corner, fewer weeds, or a later variety of wheat. Seventy years of observations could describe what had happened. They could not isolate what a manure does without additional assumptions about soil, weather and the changing practices. Fisher is said to have described the job as raking over the muck heap.
Here's the difficulty Fisher faced, on our own simulated field. This is a uniformity trial: a field cut into a hundred and forty-four plots, every one sown, manured and harvested in exactly the same way. Yet the yields range from about forty-one to about sixty bushels per acre, in patches, with a drift from west to east. The soil's own variation, from one plot to the next, is about eight percent of the average. A new manure that adds four percent would be invisible in a single comparison, and a manure that happened to land on the better side of the field would look like a miracle. Real uniformity trials like this one were harvested at Rothamsted: Mercer and Hall cut five hundred plots of wheat in 1910 and published them in 1911. That's what any experiment on land is up against.
Fisher's answer was not a cleverer analysis of the old records. It was to design the data. In 1926 he wrote: No aphorism is more frequently repeated in connection with field trials, than that we must ask Nature few questions, or, ideally, one question, at a time. The writer is convinced that this view is wholly mistaken. Nature, he suggests, will best respond to a logical and carefully thought out questionnaire. And, twelve years later, more bluntly: to consult the statistician after an experiment is finished is often merely to ask him to conduct a post mortem examination. He can perhaps say what the experiment died of. This part is about the questionnaire: how to design an experiment so that its answer is unambiguous.
Numbers: uniformity trial: yields 41–60, CV 8%
1Three principlesBachelor's5 min
Take our field, now painted by its hidden fertility, which no farmer can see. We want to compare two varieties of wheat, A and B. In truth, B yields two bushels per acre more than A, on every plot. The natural layout is tidy: A on the west half, B on the east, easy to sow and easy to harvest. The experiment reports that B beats A by seven point eight bushels. Nearly four times the truth. Swap the halves, and A wins by four point three. The comparison measures the variety plus the soil it happened to be sown on, and nothing in the data can pull the two apart. That's confounding, and it's not noise: a bigger field, laid out the same way, would give the same wrong answer more precisely.
Fisher's remedy. Let chance decide: choose the seventy-two plots that get variety B by lot, with dice, cards or a random number table, so that every plot has the same chance of either variety. Here is one such layout: untidy, and harder to sow. Now repeat the whole experiment on four thousand different random layouts. The estimates scatter, but around the truth: their average is one point nine nine, with a standard deviation of point seven one. The tidy layout's seven point eight is far out in the tail. Any one random layout still has an error, but the error is now chance, and chance has a distribution we can compute. That's the point. Over the randomization, the estimate is unbiased whatever the soil is like, even though no one has measured the soil.
The first principle, replication; the plot noise is independent in this simulator. With one plot of each variety, the comparison is hopeless. With n plots of each, chosen at random, the standard deviation of the difference falls like sigma times the square root of two over n, Part 8's law. Here sigma combines finite-field fertility variation and independent plot noise: the effective variation of one plot, is about four point three bushels. The simulated dots follow the curve: six bushels of uncertainty with one plot each, point seven with seventy-two. And replication does a second job, which Fisher thought just as important: by comparing plots that got the same treatment, it measures the error, so the experiment carries its own yardstick.
The third principle, local control. Randomization makes the comparison fair, but the soil's variation is still in the error. You can remove much of it by comparing like with like. Pair each plot with its neighbour to the east, and within every pair toss a coin for which gets variety B. Neighbours share their soil, so within a pair the soil nearly cancels, and what's left is the variety, plus a little noise. The standard deviation of the estimate falls from point seven one to point three six. The same field, the same hundred and forty-four plots, twice the precision: as good as quadrupling the size of the experiment. And randomization hasn't gone away: it now works within each pair. Restrict the randomization to match the field, and analyse the way you randomized.
Fisher wasn't the first to randomize. In 1884 the philosopher Charles Sanders Peirce and his student Joseph Jastrow tested whether a person could feel a tiny change in a weight pressing on a finger. To keep the subject from anticipating, they decided whether each change was up or down by drawing cards from a shuffled pack. It's an early documented experiment randomized on purpose, by a chance device, and it was blinded too. What Fisher added, forty years later, was the realization that the randomization is not just a safeguard. It is the probability model on which the analysis rests. That's the next chapter.
So, three principles. Replicate, to shrink the error and to measure it. Randomize, so that the expected estimate over all layouts is the true effect, tau, whatever confounders lurk, seen or unseen. Control locally, grouping similar units into blocks, so the error is only the variation within blocks. And analyse the experiment the way it was randomized. The modern summary, from George Box and his co-authors: block what you can, randomize what you cannot.
Numbers: true gain 2: systematic 7.8 (swapped −4.3); 4,000 random layouts mean 1.99, SD 0.71; n = 1 → 6.1, n = 72 → 0.70; pairs SD 0.36
2Randomization as inferenceBachelor's5 min
Fisher's argument needs no model of the soil, assuming no interference between plots and well-defined treatments. Each plot has two potential yields: what it would give with variety A, and what it would give with B. Jerzy Neyman wrote experiments this way in 1923. We see only one of the two, the one the randomization chose. Now suppose the variety does nothing whatever, on any plot: each plot's two potential yields are equal. That's Fisher's sharp null hypothesis, sharper than a statement about averages. If it's true, the twenty yields we harvested would have been exactly the same under any other labelling. The yields are fixed numbers; the only randomness is in which labels went where, and we chose those labels ourselves, by lot.
A small trial. Twenty plots on a corner of the field, ten given variety B by lot, ten given A. B's plots average fifty-three point five, A's fifty point eight: an observed difference of two point seven one bushels. If the variety did nothing, these same twenty numbers, split by some other labelling, could have shown any of a range of differences. How unusual is ours among them? We don't need a formula. We can count.
Here are the twenty yields as tokens, B's on top. Shuffle the labels, and recompute the difference. Shuffle again, and again. Each shuffle is a labelling the randomization could just as well have produced. There are twenty choose ten, a hundred and eighty-four thousand seven hundred and fifty-six, ways to choose ten plots out of twenty, all equally likely. A computer can try every one. Here's the exact distribution of the difference under the sharp null: the randomization distribution. Six thousand three hundred and twenty-two labellings give a difference at least as large as ours, in either direction: a p-value of point zero three four, exact, with no assumption about the soil, normal or otherwise. Student's t-test, which assumes normal errors, gives point zero three one. Fisher noticed this agreement in 1935, and argued that the t-test is best thought of as an approximation to the randomization test, whose validity comes from the coin.
Randomization's other gift is balance, on variables nobody measured. Take two hundred of the World's adults, and split them a hundred and a hundred by lot, five thousand times, as if for a trial. The two groups' mean heights differ by a centimetre or so, with a standard deviation of one point three; their mean incomes differ by a few thousand. Splits more than two standard deviations apart occur four point eight percent of the time: close to a normal benchmark, while the randomization distribution remains the actual yardstick, so the test's p-value already accounts for them. We never told the randomizer about height or income. It balances them anyway, along with blood pressure, diet, genes and everything else, not perfectly in any one split, but in a way whose imperfection is known.
Compare a human allocator. Suppose a well-meaning doctor gives the treatment to the hundred patients who look strongest, and suppose that means the tallest. The groups now differ in height by sixteen centimetres, twelve standard deviations of the random gap. Anything related to height, or to whatever the doctor was judging, now travels with the treatment, and the trial will credit the treatment for it. The selection needn't be conscious, or even about anything the doctor could name. Only a random device is guaranteed to know nothing about the patients.
So the logic of a randomized experiment is self-contained. The p-value is a count: the share of possible labellings that give a difference at least as extreme as the one observed. The only probability in it is the experimenter's own coin. In the 1930s Eden and Yates checked it on real wheat data. Later theory clarifies that under finite-variance and no-dominant-observation conditions, the large-sample studentized randomization distribution of the t statistic approaches a standard normal, close to a large-df t reference. So the familiar t-test and F-test can be useful approximations without normal errors under these conditions. Exact finite-sample t and F references still need their model assumptions. When the labellings are too many to count, sample ten thousand of them at random, as in Part 10. On the Coverage Board, a randomization test on skewed data keeps its five percent promise, as we'll see at the end of this part.
Numbers: 20 plots: difference 2.71; 6,322 of 184,756 labellings, p = 0.034 (t: 0.031); height-gap SD 1.32 cm, 4.8% beyond 2 SD; a chooser's gap 16.1 cm
3One-way ANOVABachelor's6 min
The analysis of variance. Four fertilizers this time: none, nitrogen, phosphate, and the full mixture N P K. Twenty-four plots, six for each fertilizer, placed by lot. That's a completely randomized design. Lay the yields out by fertilizer. Their means differ: forty-nine point five with nothing, about fifty-three with nitrogen or the mixture. But the plots within each group differ too, by as much. Is there any real difference among the four fertilizers, or is this the soil? Notice the question is about four means at once. Six separate t-tests would be the wrong tool, as chapter four will show.
Fisher's idea was to split the variation itself. Each plot's distance from the grand mean is the sum of two pieces. First, its fertilizer's distance from the grand mean, the gold arrows: variation between groups. Second, the plot's own distance from its group's mean, the red lines: variation within groups, which can only be the soil and the noise. Square both sides and sum over all twenty-four plots, and the cross term vanishes, because within each group the residuals sum to zero. So the squares add. That's Pythagoras, and it means the right picture is geometric.
Write the twenty-four deviations from the grand mean as one vector, in twenty-four-dimensional space; we can only draw three of the dimensions. The between-groups part, the group means repeated six times each, lives in a subspace with only three dimensions, four group means minus one for the grand mean. It's a projection of the data, exactly as in Part 12. The within-groups residuals are perpendicular to it, in the other twenty dimensions. So the total sum of squares, one hundred and seven point eight, is the between sum of squares, forty-six point six, plus the within sum of squares, sixty-one point two. And the dimensions add the same way: twenty-three degrees of freedom are three between plus twenty within. That's the orthogonal geometry behind Cochran's theorem. Normal errors also give the independent chi-squared laws.
Now the normal-theory test: assume independent Gaussian errors with the same variance in all groups. Divide each sum of squares by its degrees of freedom. The between mean square is forty-six point six over three, fifteen point five. The within mean square, sixty-one point two over twenty, three point oh six, is the pure error: an estimate of sigma squared, whatever the fertilizers do. Their ratio, F, is five point oh seven. If the fertilizers made no difference, the between mean square would also estimate sigma squared, and the ratio would follow Part 8's F distribution with three and twenty degrees of freedom, shown here. An F of five or more happens less than one time in a hundred: p is point zero zero nine. Fisher named the distribution's ancestor, z; Snedecor named it F, for Fisher.
The whole calculation fits in a table, one row per source of variation: degrees of freedom, sums of squares, mean squares, and F. The total row is the sum of the rows above it, in both the degrees of freedom and the sums of squares. The first published table of this kind appeared in 1923, in Fisher and Mackenzie's study of potatoes grown with different manures. Within a decade agricultural stations around the world were printing them, and the analysis of variance table is still the standard summary of an experiment.
The analysis of variance is also a regression. Code each fertilizer with a dummy variable, leaving none as the baseline, and regress the yields on the dummies. The intercept is the unfertilized mean, forty-nine point four five, and each coefficient is a fertilizer's gain over nothing: three point two for nitrogen, one point nine for phosphate, three point five for the mixture. R squared is the between sum of squares over the total: point four three two. And Part 12's nested F-test, comparing this model with the intercept alone, gives exactly the same five point oh seven. ANOVA and regression are one linear model, seen from two sides. Fisher's tables became regression software.
Why does the ratio work? Write the balanced model with independent mean-zero, equal-variance errors as a grand mean, plus a fertilizer effect alpha summing to zero, plus noise. The within mean square always estimates sigma squared, whatever the effects. The between mean square estimates sigma squared plus n over k minus one times the sum of the squared effects: inflated by real differences, and by nothing else. Under Gaussian errors, the mean of F includes the denominator correction, nu over nu minus two. It approaches one under the null as error degrees of freedom grow, and increases with the effects relative to the noise. That growth, the noncentrality, is what determines an experiment's power, the subject of chapter twelve.
Numbers: SST 107.8 = 46.6 + 61.2; F = 5.07 on (3, 20), p = 0.009; R² = 0.432
4Contrasts and many comparisonsMaster's6 min
The F-test says the four fertilizers differ somehow. It doesn't say how. For that, ask sharper questions: contrasts, weighted sums of the group means whose weights add to zero. Each contrast has its own sum of squares, with one degree of freedom; its t and F references assume independent Gaussian, equal-variance errors. First: do fertilizers help at all? Weights minus three, one, one, one compare the control with the average of the rest. The estimate is eight point six, in units of the sum, and F is twelve, p point zero zero two. Second: among the fertilized, is nitrogen alone different from the two with phosphate? Barely: F is point three four. Third: compare phosphate alone with NPK, which changes both nitrogen and potash. F two point seven six, not clear. These three contrasts are orthogonal, their weight vectors are perpendicular, so their sums of squares add up exactly to the between-groups sum of squares. Pythagoras again: three perpendicular questions, chosen before the data, split the treatment variation into orthogonal pieces; under Gaussian errors their numerator sums of squares are independent.
Here's the whole sum of squares as a bar, a hundred and seven point eight. The fertilized-versus-none contrast takes thirty-seven of it, the other two contrasts one and eight and a half, and the residual the remaining sixty-one. With k groups there are always k minus one orthogonal contrasts, and many ways to choose them. The honest way is to choose them before the experiment, from the questions it was built to answer. Choose them afterwards, because the means looked interesting, and the same arithmetic means much less, which is the problem of the rest of this chapter.
Now the common situation. A control and four new fertilizers, A to D, six plots each. The experimenter wants to know which differ from which: ten pairs. Run the t-test using the common ANOVA error on a pair noticed after looking, C against D, and you get p about point zero zero nine: significant! But C against D was chosen because it looked big. With ten pairs to look at, something may look big. How often, if nothing is going on at all?
The relevant error rate is the family-wise error rate: the chance of at least one false rejection among all the comparisons. Ten independent five percent tests would make at least one false rejection forty percent of the time. The pairwise tests aren't independent, they share groups, but simulating ten thousand experiments with no real differences, five groups of six, at least one unadjusted t-test comes out significant twenty-six and a half percent of the time. Promise five percent, deliver twenty-seven. Tukey's method, which we'll build next, holds the whole family to four point nine five percent. Both rows use independent normal, equal-variance groups and the common pooled error on the Coverage Board.
In these Gaussian, equal-variance comparisons, simultaneous protection widens the yardstick. An interval for a difference of two means is the difference plus or minus a multiplier times its standard error. For one pair chosen in advance, the multiplier is Student's t, two point oh six. To compare each of four fertilizers with the control, Charles Dunnett's 1955 method uses about two point six. To cover all ten pairs, John Tukey's uses two point nine four. The blunt Bonferroni correction for ten tests, Part 10, is a little wider, three point oh eight. And Henry Scheffé's 1953 method covers every possible contrast, even ones invented after seeing the data, with three point three two. The wider the family of questions you protect, the wider every interval must be. That's the price of looking.
Tukey's honestly significant difference. Declare two means different if their gap exceeds q times the standard error of one mean, where q is a quantile of the studentized range: the range of k normal means divided by its estimated standard error. Since the largest gap is the range, controlling the range controls every pair at once. For five groups and twenty-five degrees of freedom, q is four point one five, so the honestly significant difference is three point five bushels. In the grid of all ten gaps, two exceed it: C against the control, five bushels, and C against A. One more pair, C against D, passes an unadjusted t-test and fails Tukey's: red. It might be real. But this experiment can't honestly claim them.
If the only question is which new fertilizers beat the control, the family is smaller: four comparisons, not ten. Charles Dunnett's 1955 method, devised while he worked for a pharmaceutical company, uses that smaller family, and its narrower multiplier. Here only C beats the control, with an adjusted p of point zero zero one; A, B and D don't. The method matches the question, and the question should be written down before the harvest.
So, a short guide. For a few contrasts planned in advance, each usual-level test gives an individual guarantee; use Bonferroni or Holm for a family guarantee. For all pairs, Tukey. For each treatment against a control, Dunnett. For anything at all, including contrasts suggested by the data, Scheffé, and pay for it. And when there are thousands of tests, as in genomics, controlling the chance of even one false rejection is too strict. Benjamini and Hochberg's false discovery rate makes a different promise, and Part 33 builds it.
Numbers: 37.09 + 1.04 + 8.45 = 46.59; FWER 26.6% vs Tukey 4.95%; multipliers t 2.06, Dunnett 2.61, Tukey 2.94, Bonferroni 3.08, Scheffé 3.32; HSD 3.50
5BlockingBachelor's6 min
Here's a field with a steep slope in fertility, from about forty-two bushels on the west edge to fifty-eight on the east. Four treatments, A to D, six plots each. The slope runs east to west, so each north-to-south strip of four plots is nearly uniform. Make each strip a block. Put all four treatments in every block, and randomize their order within it, separately for each block. That's a randomized complete block design: complete, because every block holds every treatment. The true gains over A are two, three and one and a half bushels. Here's the harvest.
Analyse the harvest two ways. Ignore the blocks, and run Chapter three's one-way analysis. The treatment sum of squares is ten point nine, but the residual is eight hundred and fifty-nine: the soil's slope is in the error. F is point zero eight, p point nine seven. Nothing to see. Now include the blocks, as the design says we must. The block row takes eight hundred and twenty-nine of the sum of squares. The treatment sum of squares is exactly the same ten point nine, but the residual has fallen to thirty, the error mean square from forty-three to two point zero one. F is one point eight one, p point one nine. This is the first seeded harvest, chosen before seeing its result. Better precision still does not guarantee significance. The same twenty-four numbers, the same treatment comparison. The difference is that the design measured the soil, and the analysis took it out of the error.
The first harvest did not detect the real differences. How often does each design succeed? Repeat each design four thousand times on this field. The completely randomized design, analysed one way, detects the treatment differences ten percent of the time. The block design detects them seventy-four percent of the time. The average error mean square falls from thirty-three to two point two five. Since variance falls like one over the number of plots, the block design is about as precise as a completely randomized one with fifteen times as many plots. Blocking also costs planning and error degrees of freedom; here its precision gain is worth fifteen fields.
The additive model behind the block design. Its exact F reference assumes independent Gaussian errors of equal variance; unreplicated interactions cannot be separately estimated. A yield is a grand mean, plus a treatment effect, plus a block effect, plus noise. The block effect shifts every treatment in that block by the same amount. The total sum of squares now splits into three perpendicular pieces: treatments, blocks and error. So do the degrees of freedom. The error is whatever's left: how far the treatment differences vary from block to block. And the key line: a difference between two treatment means contains no block effects at all. Every treatment saw every block once, so the soil cancels exactly, the same reason the pairs in chapter one worked.
Blocking is older than Fisher. In 1876 Charles Darwin published his experiments on cross- and self-fertilization. For maize, he grew fifteen pairs of seedlings, one from a crossed parent and one from a self-fertilized parent, planted side by side in four pots, and later measured their heights. He asked his half-cousin Francis Galton for help with the numbers. Each pair is a block of two: the two plants share the same soil, light and watering. Here are the fifteen differences, crossed minus selfed, in eighths of an inch. Thirteen are positive; their mean is twenty point nine. But two pairs strongly favour the self-fertilized plant. Is the difference real?
The analysis must respect the blocks: compare within each pair. The paired t statistic is two point one five, with p just under point zero five. Fisher re-analysed Darwin's data in 1935 as a randomization test within blocks. If crossing did nothing, each pair's two labels could equally well have been swapped, which flips the sign of that pair's difference. Fifteen pairs give two to the fifteenth, thirty-two thousand eight hundred and twenty-nine, sign patterns. Eight hundred and sixty-three of them give a total at least as large as Darwin's, so the two-sided p-value is point zero five three, close to the t-test's. Part 10 met this test; here it's the analysis that matches a block design. Darwin hadn't randomized which seedling went where in the pot, so this historical sign-flip calculation assumes independent differences with signs equally likely under the null; assuming merely that placement didn't matter is insufficient on its own.
When should you block? Whenever you know something varies: strips of soil, days of the week, batches of material, litters of mice, the technician running the assay, the patient in a crossover trial. A good block is as uniform as possible inside, however different blocks are from each other. Blocks cost degrees of freedom: b minus one of them leave the error. So a useless block loses a little precision, but an important source of variation that's ignored can lose a great deal, as we just saw. And when a block is too small to hold every treatment, a pot with room for two of four varieties, say, Frank Yates's balanced incomplete block designs of 1936 arrange the treatments so that every pair meets equally often.
Numbers: first seeded harvest: ignoring blocks F = 0.084, p = 0.968; RCBD F = 1.806, p = 0.189; power 10% vs 74%; MSE 33.4 vs 2.25; Darwin t = 2.15, 863/32,768, p = 0.053
6Latin squares and crossoversMaster's5 min
Sometimes the soil varies in two directions. This field grows richer to the east, and also to the south. We have five varieties and twenty-five plots. Blocks made of rows would leave the east-west slope in the error; blocks made of columns would leave the north-south one. The answer is a Latin square: arrange the five letters so that each appears exactly once in every row and once in every column, like a Sudoku. Then every row is a complete block, and so is every column. Compare variety A with variety B, and both sets of soil effects cancel, because each variety met every row and every column exactly once.
The analysis of variance now has a row for rows, a row for columns, and a row for varieties. Assuming an additive model with independent normal equal-variance errors, rows and columns take two hundred of the sum of squares, leaving a residual of just six point three on twelve degrees of freedom. The varieties' F is seventeen point eight. Ignore the square, and analyse the same twenty-five numbers one way: F is point eight eight, p point four nine. Over four thousand repetitions, the Latin square detects the varieties ninety-six percent of the time, the completely randomized design twenty percent. The price is degrees of freedom: twelve for error instead of twenty, which is especially costly for very small squares. And underneath, Pythagoras once more: four perpendicular pieces.
Which Latin square? Norwegian agronomists liked the Knut Vik square, where each letter moves like a knight in chess, spreading the varieties evenly over the field. Or the cyclic square, each row the previous one shifted by one place. Fisher objected to both. A systematic square can line up with a systematic pattern in the soil, a diagonal ditch, say, and then the error estimate is wrong, too large or too small, with no way to tell. Randomize the layout. In total, there are a hundred and sixty-one thousand, two hundred and eighty Latin squares of order five. In practice, take one square and shuffle its rows, its columns and its letters at random, the recipe in Fisher and Yates's statistical tables. This samples the chosen square's permutation class, not uniformly all Latin squares. The exact F reference also needs the additive Gaussian model.
Latin squares are also a famous piece of mathematics. In 1782 Leonhard Euler asked whether thirty-six officers, from six regiments and of six ranks, could stand in a six-by-six square with every regiment and every rank appearing once in each row and each column. That needs two Latin squares that fit together, called orthogonal. Euler conjectured it was impossible for six, and for ten, fourteen and every size two more than a multiple of four. In 1900 Gaston Tarry checked every case and confirmed that six is impossible. But in 1959 Raj Chandra Bose, Sharadchandra Shrikhande and Ernest Parker constructed them for ten and every larger case. Bose and Shrikhande were statisticians, led to the problem by the design of experiments. In a field, a Graeco-Latin square blocks three ways at once.
The same idea runs medical trials. In a crossover trial, each patient receives both treatments, one in each period, separated by a washout so the first wears off, and the order is randomized. The comparison is within each patient, so the enormous variation from person to person, in age, weight and severity, cancels. Each patient is a block. Half the patients get A then B, half B then A, so that a period effect, the disease improving on its own, say, also cancels. Each pair of patients with opposite orders is a two-by-two Latin square: rows are patients, columns are periods.
The crossover model: a period effect, a treatment effect, a subject effect, and noise. The treatment difference is estimated by half the difference between the two sequence groups' within-patient changes; the subjects and the periods both cancel. The danger is carryover: if the first drug's effect lingers into the second period, the cancellation fails, and in a two-period design the carryover can't be separated from the treatment effect. The remedies are a long washout, or designs with more periods, like Evan Williams's 1949 squares, which are balanced so that every treatment follows every other equally often. Crossovers are standard for chronic conditions and for bioequivalence studies of generic drugs; they're useless when a treatment cures.
Numbers: F = 17.8 vs 0.88 one-way; power 96% vs 20%; 161,280 squares of order 5
7FactorialsBachelor's7 min
First, why a single pass of one-factor-at-a-time optimization can fail. The island's bakery wants the best bread. Its quality depends on two knobs, oven temperature and baking time, through a surface it can't see; we'll show it, brightest where the bread is best. The baker starts at one eighty degrees and twenty minutes, and the bread is poor. Following the old aphorism, he varies one factor at a time. Holding time at twenty minutes, he tries temperatures from one sixty to two forty, and finds the best at two twenty-five. Then, holding that temperature, he varies the time: best at twenty-six and a half minutes, quality seventy-nine and a half. He stops, satisfied. The real best is at two oh five degrees and thirty-one minutes, quality eighty-five. The bright ridge runs diagonally: a hotter oven wants a shorter bake. The two knobs interact. Moving one knob at a time, along the grid lines, you can only crawl up a diagonal ridge, and you can easily stop too soon. Repeating coordinate searches can converge on this smooth surface, but this one pass did not.
The factorial alternative changes both knobs together, in every combination. Two levels of temperature, one eighty-five and two fifteen, crossed with two levels of time, twenty-two and thirty-four minutes: four bakes at the corners of a square. Here are the true qualities. The temperature effect is the average change from the cool side to the hot side: fourteen points. The time effect, nineteen. And the interaction: the hotter oven gains twenty-nine points on a short bake but nothing on a long one, and half that change, minus fifteen, is the interaction. A big interaction is the diagonal ridge, detected by four bakes. This baseline-and-one-change design cannot estimate the interaction, because it omits the corner where both knobs have moved.
Now the classic agricultural case, with three factors. Nitrogen, phosphate and potash, each either withheld or applied. Every combination makes a two-to-the-three factorial: the eight corners of a cube. With two plots of each, sixteen plots. Frank Yates named each corner by the nutrients present: one in brackets for none, n for nitrogen alone, n p for both, up to n p k. In our simulation, the true averaged high-minus-low effects are six bushels for nitrogen, two for phosphate and half a bushel for potash; the NP interaction effect is two, half the four-bushel difference between the nitrogen effects at the two phosphate levels. Here are the average yields at each corner.
Every effect is a contrast between two halves of the cube. The nitrogen effect: the average of the four corners with nitrogen, the front face, minus the average of the four without. Forty-three minus thirty-six point eight: six point two. An interaction uses the sign of a product: corners where nitrogen and phosphate are both present or both absent, against corners where exactly one is. The NP interaction is one point three four. Each of the seven effects uses all sixteen plots, eight against eight. Nothing is set aside to answer only one question. So each effect has the standard error of a difference between two means of eight plots, estimated from the replicates as point five three.
Frank Yates, Fisher's successor at Rothamsted, gave a way to compute all the effects by hand. Write the eight yields in standard order. In each pass, write the sums of consecutive pairs, then their differences: second minus first. Do it again on the new column. And a third time, one pass per factor. The top of the last column is the grand total; every other entry, divided by four, is an effect, in standard order: N, P, NP, K, NK, PK and NPK. Nitrogen six point two, phosphate three point oh, their interaction one point three; the rest are small. Yates published it in 1937, in The Design and Analysis of Factorial Experiments. It's the Walsh-Hadamard transform for the group of the cube's corners, later familiar in fast transform algorithms.
Interactions are best seen in a plot: the mean yield without and with nitrogen, one line for the plots without phosphate, one for the plots with it. If the two nutrients acted separately, the lines would be parallel. They diverge: nitrogen is worth more when phosphate is present, because a crop short of phosphate can't use all the nitrogen it's given. So the main effect of nitrogen, six point two, is an average over the two phosphate levels. When the interaction is large, that average can mislead, and the honest report gives the effect of each factor at each level of the other.
How do you judge seven effects at once? Cuthbert Daniel's 1959 idea: sort the absolute effects and plot them against the quantiles of a half-normal distribution. If no effect were real, all seven would be noise, and the points would lie roughly on a straight line through zero. Nitrogen and phosphate stand far off the line: evidence of active effects, rather than a calibrated multiple-testing guarantee. The NP interaction is borderline here, one point three four against a standard error of point five three, about two and a half standard errors: real in truth, but just at the edge of what sixteen plots can see. In industrial experiments, which often have no replicates, Daniel's plot is a useful screening plot, relying on effect sparsity rather than guaranteeing that every marked effect is real.
So the factorial wins twice. With sixteen plots, one factor at a time would use four settings, the baseline plus one change per factor, four plots each. Each effect is a difference of two means of four: standard error point seven one sigma. The factorial compares eight plots with eight for every effect: point five oh sigma. Under an additive mean model these target the same effects, and the one-factor design needs twice the plots. Fisher called this hidden replication: every plot replicates every comparison. And only the factorial measures interactions. Fisher added a third advantage: because each effect is averaged over the other factors' levels, its reported main effects average over the tested factor combinations; interactions still require reporting simple effects. That's the questionnaire.
Numbers: OFAT ends at 225 °C, 26.5 min, quality 79.6 vs 85; 2² effects 14.3, 19.0, −15.0; NPK: N 6.21, P 2.95, NP 1.34, SE 0.53
8Fractional factorialsMaster's6 min
Factorials have a cost. A full factorial in k factors at two levels needs two to the k runs. Seven factors need a hundred and twenty-eight; ten need over a thousand. Yet if what you want is the main effect of each factor, you need only k plus one numbers. Most of a large factorial goes to estimating four-way, five-way and six-way interactions. And experience says those are almost always negligible: a few effects are large, and high-order interactions rarely matter. That's the principle of effect sparsity, and it licenses running only a fraction of the factorial.
Take four factors, A, B, C and D. The full factorial is sixteen runs: draw it as two cubes, one for each level of D. Now run only half: the eight corners where the level of D equals the product of the levels of A, B and C. Each cube gets four corners, alternate ones, never two joined by an edge, so every factor is still balanced: four runs high, four low. This is a two to the four minus one fractional factorial, introduced by David Finney at Rothamsted in 1945. What do we lose?
What we lose is aliasing. In the eight runs we kept, the column for D equals the column for A times B times C. Multiply both sides by D: the column A B C D is plus one in every run. That's the defining relation, I equals A B C D. Multiply any effect by it, with the rule that a squared letter vanishes, because plus or minus one squared is one: A times A B C D is B C D. So in these eight runs, the column for A is identical to the column for the three-factor interaction B C D, and what we estimate is their sum. They're aliases. The two-factor interactions pair up too: A B with C D, A C with B D, A D with B C. The half fraction can't tell the members of a pair apart. It can only tell us their sum.
Does it matter? Here's a simulated process in four factors: A truly adds four, C two, D three, and A and B interact, one and a half; everything else is zero. The table shows the full sixteen-run estimates and the eight-run half fraction's. The half fraction finds the same important factors, A, C and D, with estimates close to the full design's, at half the cost. But its A B row, one point six eight, is really A B plus C D, and the eight runs can't say which. Here it's A B, because we built it. A real experimenter would need knowledge, or more runs. The standard remedy is to run the complementary fraction with D changed to minus A B C. Reversing D alone splits these pairs; reversing all four factors would keep the same even-word fraction.
George Box and Stuart Hunter classified fractions by their resolution. In a resolution three design, main effects are aliased with two-factor interactions: good only for a first screening. In resolution four, main effects are clear of two-factor interactions, but those are aliased with each other. In resolution five, main effects and two-factor interactions are all clear of each other. The resolution is the length of the shortest word in the defining relation. Ours, A B C D, has four letters: resolution four, which is exactly what the table showed.
Push it to the limit. Seven factors in eight runs: a two to the seven minus four design. Start with the full factorial in A, B and C, and give the four extra factors the interaction columns: D is A B, E is A C, F is B C, and G is A B C. Every column is balanced, four high and four low, and every pair of columns is orthogonal, so the seven column contrasts are uncorrelated under equal-variance uncorrelated errors, and independent under Gaussian errors, each from all eight runs. It's resolution three, saturated: no degrees of freedom left for error, and every main effect is aliased with interactions. It's a screening design: it tells you which of many factors deserve a proper experiment.
Fractional factorials have two to the p runs. In 1946 Robin Plackett and Peter Burman, working on wartime problems for Britain's Ministry of Supply, tabulated orthogonal designs for many run counts divisible by four. Here's their twelve-run design for up to eleven factors: each row is the first row shifted by one place, plus a final row of all lows. Its columns are exactly orthogonal: X transpose X is twelve times the identity, so every main effect is estimated with the full precision of all twelve runs. Unlike a regular fraction, it has no simple aliasing: each two-factor interaction is spread in small pieces over many columns. Plackett–Burman designs are still standard for screening in chemistry and manufacturing.
Numbers: half fraction A 4.21 (full 4.51), AB + CD 1.68; Plackett–Burman XᵀX = 12I
9Response surfacesMaster's5 min
Agriculture gets one harvest a year. Industry can run an experiment every afternoon. In 1951 George Box, a chemist turned statistician, and K. B. Wilson, both at Imperial Chemical Industries, published a strategy for finding the best operating conditions of a chemical process. Experiment in stages, each designed from what the last one found. Far from the optimum, a small piece of any smooth surface looks like a tilted plane: fit a plane, and walk uphill. Near the top, the surface looks like a quadratic bowl, upside down: fit a quadratic, and find its peak. Let's give the island's baker the method.
Now the surface is hidden, as it is for the baker. Start at his current recipe, one eighty-five degrees and twenty-two minutes. Bake at the four corners of a small square around it, and three times at the centre: seven bakes. Work in coded units, so each factor runs from minus one to plus one. Fit a plane by least squares: quality forty-four, plus twelve point six per unit of temperature, plus fifteen point six per unit of time. Is a plane good enough? Compare the corners' average with the centre's. If the surface curved strongly, they'd differ. They differ by about four points, small beside the slopes. So the plane is a fair local description, and its gradient points uphill. The repeated centre bakes also measure the noise, which is how the method knows a difference from an accident.
Stage two: walk uphill. The path of steepest ascent leaves the centre along the fitted gradient, twelve point six units of temperature for every fifteen point six of time, in coded units. Bake one recipe at each step along it. Quality climbs fast: forty-five, sixty-two, seventy-six, then eighty-five, twice. Then it falls. The best is at step four, two oh five degrees and thirty-one minutes, quality eighty-five. The plane predicted endless improvement; the fall means we've reached the curved region near the top, where a plane is no longer good enough.
Stage three: Box and Wilson's central composite design, centred on the best point found. A small factorial square, plus four axial points, out along each axis at plus or minus root two in coded units, so all eight lie on a circle. Plus five bakes at the centre. Thirteen bakes, with five distinct levels of each factor: enough to fit a full quadratic, with its curvatures and its interaction. Putting the axial points at root two makes the design rotatable: under independent equal-variance errors, fitted-mean prediction variance depends only on the distance from the centre in coded units.
Fit the quadratic by least squares: an intercept, two slopes, two curvatures and an interaction. In matrix form, b zero, plus x transpose b, plus x transpose B x, with the curvatures on B's diagonal and half the interaction off it. Set the gradient to zero: the stationary point is minus a half B inverse b. Is it a peak, a valley or a saddle? B's eigenvalues tell. Both are negative, so it's a maximum. One is three times the other: the surface falls steeply in one direction and gently in the other, along the ridge, where temperature and time can trade off. Box called this canonical analysis.
The fitted peak is at two oh three degrees and thirty-one point seven minutes. The quadratic predicts a quality of eighty-five point two there; the hidden truth at that recipe is eighty-four point nine. Now reveal the surface: the true optimum, two oh five and thirty-one, is right beside it. Twenty-nine bakes in all, in three stages. The plane was wrong, and the quadratic is wrong too: the true surface isn't a quadratic far from the top. But each was useful exactly where it was used. That's George Box's famous line: all models are wrong, but some are useful.
Numbers: first-order fit 43.9 + 12.6x₁ + 15.6x₂; best on the path 85.3; stationary point 203.0 °C, 31.7 min, predicted 85.2 (truth 84.9); 29 bakes
10Split plotsMaster's5 min
Some factors can only be applied to big pieces of land. Irrigation runs along a channel: you can water a whole strip, not one small plot here and another there. So randomize irrigation over large whole plots, two per block, one wet and one dry. Then split each whole plot into four subplots, and randomize four varieties of wheat among them, separately in each whole plot. Two randomizations, at two scales: a split-plot design, which Frank Yates described at Rothamsted in the 1930s. It's convenient, and very common. And it is very commonly analysed wrongly.
The model has two error terms. Each whole plot has its own random error, w, shared by its four subplots: the soil of that strip, the way its channel ran. Each subplot also has its own error, e. Two strata of error, sigma w and sigma, taken independent and Gaussian here for the exact F references. Irrigation is compared between whole plots, so its comparison carries the whole-plot error: the variance involves sigma w squared, divided by the number of blocks, just four. Varieties are compared within whole plots, so w cancels, and only the small subplot error remains. The split plot measures the subplot factor precisely, and the whole-plot factor coarsely.
Here's one simulated split plot, with a real irrigation effect of two bushels. The common mistake: analyse it as if all thirty-two subplots had been randomized independently, a completely randomized design. Irrigation gets an F of twenty-two, on one and twenty-four degrees of freedom: p of eight in a hundred thousand. The right analysis compares irrigation with the variation between whole plots, the whole-plot error, which has just three degrees of freedom. F is six point eight; p is point zero eight. The effect is real here, but the first analysis claims far more certainty than the experiment contains, by dividing by an error made mostly of the small subplot variation, and by counting twenty-four degrees of freedom for a comparison that has three. Only eight whole plots were ever randomized to irrigation or not. That is the real sample size for irrigation, however many subplots each one holds.
How bad is the mistake? Simulate ten thousand split plots in which irrigation does nothing at all. Analysed as a completely randomized design, irrigation comes out significant at five percent in twenty-six percent of them: a five percent promise broken five times over. With the whole-plot error, the rate is five point oh one percent: kept. Both rows go on the Coverage Board. The general lesson is one of the most important in applied statistics: the error term must come from the scale at which the treatment was randomized. It returns with mixed models in Part 25, and with clustered data everywhere.
Why does it fail? Look at what each mean square estimates. With no real effect, irrigation's mean square estimates sigma squared plus four sigma w squared, because each whole plot's mean carries its own w. With our values, seventeen. The right analysis divides it by the whole-plot error, which estimates the same seventeen. The subplot error estimates only sigma squared, one. The completely randomized analysis pools everything left over into one error: three degrees of freedom of blocks, three of whole-plot error, and eighteen of subplot error. Dominated by the subplots, it estimates about six, not seventeen. So with no effect at all, its ratio of expected mean squares is nearly three; this is not the exact expectation of the ratio, and it's judged against an F distribution with twenty-four denominator degrees of freedom instead of three. Both mistakes push the same way.
Split plots hide wherever a factor is hard to change. In a factory, the furnace temperature is set once a day and several recipes are baked at it: temperature is a whole-plot factor. In education, a teaching method is given to a classroom, and the students in it are subplots. In biology, a diet is given to a mouse, and several tissues are measured from each one. In every case, the hard-to-change factor's real sample size is the number of times it was independently set: days, classrooms, mice. Analyse the experiment the way it was randomized, with one error stratum for each randomization. That's chapter one's last principle, and here is where ignoring it costs the most.
Numbers: wrong F = 22.3 on (1, 24), p = 8 × 10⁻⁵; right F = 6.79 on (1, 3), p = 0.08; null rejection 25.6% vs 5.01%
11Optimal designPhD6 min
Experiments also choose where to measure. Suppose we'll fit a straight line through ten observations, and we may choose the doses anywhere from minus one to one. With independent equal-variance errors, the slope's variance is sigma squared over the spread of the x's, Part 12. Spread evenly, the slope's standard error is point five oh sigma. Put half the observations at each end, and it's point three two. That's as good as two and a half times as many evenly spread observations. The catch is obvious: with all the points at two doses, you can't see whether the truth is a line at all. The best design for one model can be blind to another, a theme that runs through this chapter.
The first paper on optimal design was written in 1918 by Kirstine Smith, a Danish statistician working in Karl Pearson's laboratory in London. She asked where to place observations for fitting polynomials, of degrees up to six, and found the designs that make the worst prediction variance over the range as small as possible. The subject slept for forty years, until Jack Kiefer and Jacob Wolfowitz built a general theory around 1960. Let's rediscover her answer for a quadratic.
The model: a quadratic in x, with x anywhere from minus one to one. The coefficients' covariance is sigma squared over n times the inverse of M, the information matrix per observation, built from the vectors one, x, x squared at the design points; the design has full column rank and independent equal-variance errors. A good design makes M large. But M is a matrix: large in what sense? The most popular answer: make its determinant as large as possible. That's D-optimality, D for determinant. The determinant measures the volume of the joint confidence ellipsoid for all three coefficients: the bigger det M, the smaller the ellipsoid.
Search for it. Put the design's points at minus one, at one, and at a middle point m, a third of the observations each, and slide m. The determinant peaks with m exactly at zero. Now keep the points at minus one, zero and one, and vary how the observations are shared: a fraction w at each end, the rest in the middle. The peak is at w equals one third. So the D-optimal design for a quadratic puts a third of the observations at each end and a third in the middle. Its determinant is four over twenty-seven, point one four eight. Twenty-one evenly spaced points give point zero three nine, less than a third as much: the familiar even spread wastes most of its observations in places that tell us little.
Kirstine Smith looked at a different quantity: how precise the fitted curve is at each x, the prediction variance, scaled so designs of any size compare. For the even spread, it's worst at the ends, seven and a half, where the even design has few neighbouring points to lean on. For the thirds design, it never exceeds three, and touches three exactly at the design points, minus one, zero and one. And three is the number of parameters. That's not a coincidence.
Write the variance function as f transpose M inverse f. Averaged over the design's own points, it's the trace of M inverse times M: always p, the number of parameters, for any design with nonsingular information. So the maximum can't be less than p. Kiefer and Wolfowitz's equivalence theorem of 1960, for approximate designs with freely chosen probability weights on a compact design space: a design is D-optimal exactly when its maximum is p, reached at its support points. So maximizing the determinant, a statement about the coefficients, and minimizing the worst prediction variance, Smith's 1918 criterion, give the same design. It also gives a practical check: compute the variance function, and if it ever exceeds p, moving weight toward that x can improve the approximate design. An exact finite-run design must also respect integer allocation constraints.
There are other criteria: A for the average variance of the coefficients, E for the worst direction, I for the average prediction variance. They often agree roughly, and the theory handles them all. The real caution is that a design is optimal for the model you assumed. Three support points can fit a quadratic exactly; they can't reveal a cubic. Practical designs add a few points to test for lack of fit. George Box and Norman Draper argued in 1959 that the bias from fitting the wrong model often matters more than the variance an optimal design minimizes. For nonlinear models the best design depends on the unknown parameters themselves, which suggests choosing each observation from the data so far. Adaptive designs, and the care their inference needs, come back in Part 58.
Numbers: slope SE 0.495σ (even) vs 0.316σ (ends); det M 4/27 = 0.148 vs 0.039; max d(x) = 3 vs 7.5
12Power and sample sizePractice5 min
Every design decision in this part was really about one question: will the experiment see the effect if it's there? Say we want to detect a five percent yield gain, two and a half bushels, with a five percent test. The power is the chance the experiment declares the gain significant when it really exists. On a completely randomized field with a plot standard deviation of four bushels, the power climbs slowly with the number of plots: forty-two plots of each variety for eighty percent. If blocking halves the standard deviation to two, twelve plots each are enough. Halving the noise cuts the plots needed by about a factor of four; the exact small-sample t calculation differs, because the number needed grows like sigma squared. Good design is cheaper than more data.
The arithmetic, from Part 10. The test rejects when the difference exceeds z times its standard error, sigma root two over n. If the true gain is delta, the power is approximately Phi of delta over the standard error, minus z. The curves on the last screen used the exact version, with the noncentral t distribution. Solve for n: two times the sum of two normal quantiles, squared, times sigma squared over delta squared. For eighty percent power at the five percent level, that's about fifteen point seven over d squared, where d is delta over sigma: the effect measured in standard deviations, Jacob Cohen's standardized effect size.
Or turn it around. Given the plots we can afford, what's the smallest gain we'd detect eighty percent of the time? That's the normal-approximation minimum detectable effect: the sum of the two quantiles times the standard error. With twenty plots per variety and sigma four, it's three and a half bushels, seven percent. With eighty plots, one point seven seven. Four times the plots buys half the detectable effect. The square-root law, again: precision is expensive, which is why reducing sigma by design beats adding plots.
In 1962 the psychologist Jacob Cohen surveyed a year of a leading journal and found that, for effects of medium size, the typical study had less than an even chance of detecting them, even if they were real. To make the problem concrete, he offered conventions: a small effect is a fifth of a standard deviation, needing about four hundred subjects per group by the normal approximation for eighty percent power; a medium effect, half a standard deviation, sixty-three; a large one, twenty-five. They're conventions, not laws. The effect worth detecting depends on the problem: a two percent yield gain is enormous on a national scale.
Low power does a second kind of damage, less obvious than missing real effects. Here are three hundred simulated experiments with ten plots per variety, where the true gain is two and a half bushels. Their power is twenty-seven percent. The gold ones are the experiments that came out significant. Their average estimate is four point five, nearly twice the truth. With so much noise, significance selects large magnitudes: mostly positive overestimates here, with some possible wrong-sign results. If only significant results are published, the published effects are exaggerated. That's the winner's curse.
Across sample sizes: with five plots per variety, the power is fourteen percent, and a significant result exaggerates the true gain two point four times; one significant result in seventy-five even has the wrong sign. With twenty plots, power is half and the exaggeration one point four. At forty-two, our planned eighty percent, the exaggeration is twelve percent; by eighty plots it is small, not mathematically zero. Andrew Gelman and John Carlin called these type M errors, of magnitude, and type S errors, of sign. An adequately powered experiment isn't only more likely to find a real effect. When it does, selection exaggeration is reduced; power alone cannot repair bias, confounding or a misspecified analysis.
Some practical rules. A power calculation needs two inputs: the effect worth detecting, and the noise. The noise comes from a pilot study or past trials, and it's uncertain itself, so plan for a range of values, not one. The effect should be the smallest one that would matter in practice, not the one you hope to find; plugging in an optimistic effect is the commonest way to design an underpowered study. And don't compute power after the fact from the effect you observed: that number is just a transformation of the p-value, and tells you nothing new. Finally, remember the trade: design reduces sigma, and only money increases n.
Numbers: n for 80%: 42 (σ = 4) vs 12 (σ = 2); MDE 3.54 at n = 20, 1.77 at n = 80; normal-approximation Cohen 393 / 63 / 25; exaggeration 2.41× at n = 5, 1.12× at n = 42
13Online experimentsPractice7 min
Around 2012, an engineer at Bing, Microsoft's search engine, suggested a small change to how ads were shown: move some of each ad's text up into its headline. The idea sat on a list for months, judged low priority. When someone finally tested it, in a two-week online experiment, revenue rose twelve percent: worth more than a hundred million dollars a year in the United States alone. The story is told by Ron Kohavi, Diane Tang and Ya Xu in their book on online experiments. Their broader point is humbling: most ideas, when tested, do nothing or do harm, and nobody can tell in advance which. So large technology companies now run tens of thousands of randomized experiments a year. They're Fisher's experiments, with users as plots.
The anatomy of an A/B test. The unit is a user, assigned by an experiment-specific randomized hash of their ID, so the same person always sees the same version. Two arms, the control and the change, usually split fifty fifty: a Bernoulli-randomized design with millions of plots. A metric chosen in advance, like revenue per user. And the estimate is the difference in means, with Welch's standard error from Part 10. Everything in this part applies. The one new problem is that the effects are tiny, a fraction of a percent, and the metrics are noisy. Even with millions of users, precision is precious.
Here's a simulated test with twenty thousand users. The change truly adds point one five to each user's monthly spend, about one and a half percent. Plot each user's spend this month against their spend last month, before the experiment began. Most of the variation in this month's spend was already there: big spenders stay big spenders. The correlation is point eight. So subtract the part of each user's spend that last month predicts, and compare what's left. Using a pre-treatment covariate avoids adjusting away treatment effects, because the change cannot have affected last month. This is regression adjustment using a baseline covariate, rather than design-stage blocking; fitted adjustment can have small finite-sample bias.
In 2013 Alex Deng, Ya Xu, Ron Kohavi and Toby Walker named it CUPED: replace each user's metric by the metric minus theta times their centred pre-experiment value, with theta the regression slope of y on x. For a fixed population-optimal coefficient, the residual variance is one minus rho squared times the original: here, about thirty-six percent of it. The plain comparison estimates point one oh four, with a standard error of point zero five six: p point zero six five, not significant. CUPED, on the same users, estimates point one four, with a standard error of point zero three four: p of four in a hundred thousand. Cutting the variance to thirty-six percent is worth two point eight times as many users. Statisticians will recognize Fisher's analysis of covariance from 1932, adapted at scale. The fitted-coefficient standard error and z-test here are large-sample approximations.
Is that one experiment typical? Repeat the whole experiment two thousand times; the histogram shows the first six hundred. The plain estimates, in red, spread widely around the truth; the CUPED estimates, in gold, cluster tightly: their standard deviation falls from point zero five seven to point zero three three. Both are centred on the true point one five. The estimates show little bias in this large simulation. Fitting theta on these same data can introduce small finite-sample bias, even with a pre-treatment covariate. The covariate was measured before the coin was tossed. David Freedman worried in 2008 that regression adjustment could mislead in experiments; Winston Lin showed in 2013 that with an interaction and robust standard errors, under regularity conditions it is at least as precise, asymptotically. It's now routine.
The most important check in online experiments costs nothing. This experiment was designed as a fifty-fifty split. The arms received fifty thousand and fifty thousand eight hundred and twenty users. A chi-squared test of the split, Part 10's goodness of fit, gives p equals point zero zero nine eight. A fair coin rarely misses by this much. That's a sample-ratio mismatch, and it is evidence of an assignment or logging problem, although a valid randomized test can occasionally flag by chance. Bots filtered differently in the two arms; a bug that crashes the new version for some browsers, so their users vanish from the logs; a redirect that loses people. If selection or logging depends on the arm, comparability can fail and the original randomization guarantee no longer applies to the recorded comparison. Check the split before reading any metric.
The old pitfalls come back at scale. Watching the p-value every day and stopping when it dips below five percent breaks the test, as Part 10 showed; Part 58 builds tests that allow it. Novelty effects: users react to anything new, then settle, so a two-day test can mislead. Interference: on a social network, treating one user changes what their friends see, so the control group isn't untreated. Parts 35 and 62 take this up. Dozens of metrics and segments: chapter four's multiplicity. And A/A tests, where both arms get the same version, check that the platform's five percent really is five percent.
The Coverage Board, with seven new rows, all tests whose promise is a five percent false-rejection rate. The randomization test on skewed data, ten plots against ten: five point two percent, kept. Its validity came from the coin. A t-test on the tidy systematic layout of chapter one, with no real difference between varieties: it rejects every single time. The soil's gradient is confounded with the varieties. All ten pairwise t-tests among five groups, unadjusted: at least one false rejection twenty-seven percent of the time, broken. Tukey's method: four point nine five percent, kept. The split plot analysed as a completely randomized design: twenty-six percent, broken. With the whole-plot error: five point oh one, kept. And the CUPED test in ten thousand A/A experiments: five point two, kept. Every broken row in this part is a design ignored by its analysis.
Numbers: ρ = 0.80; SE 0.056 → 0.034; p 0.065 → 3.9 × 10⁻⁵; worth 2.8× the users; SRM 50,000 vs 50,820, p = 0.0098
Recap, problems, and the road aheadAll tracks3 min
Part thirteen in thirteen lines. Fisher found that seventy years of records couldn't answer a question, and decided to design the data instead. Replicate, randomize, and control locally. The randomization itself gives an exact test, with no model of the soil, and it balances every variable nobody measured. The analysis of variance splits the sum of squares into perpendicular pieces, and F compares them; orthogonal contrasts ask sharper questions, and Tukey, Dunnett and Scheffé pay honestly for asking many. Blocks take the soil out of the error; Latin squares do it two ways at once, and crossovers use each patient as a block. Factorials use every plot for every question and see interactions; fractions trade aliases for runs; response surfaces climb and then fit a quadratic. Split plots need the error from the scale of their randomization. D-optimal designs put the observations where they inform; power calculations size the experiment; and online, CUPED and the sample-ratio check carry it all to millions of users.
Where it comes back. Outcomes that are counts and yes-or-no answers, in the next part; rank and resampling tests in Part 16; the design of surveys, a cousin of experimental design, in Part 18; the linear model in full in Part 23; mixed models, which handle split plots and clustered data in general, in Part 25; the false discovery rate in Part 33; potential outcomes and interference in Parts 35 and 62; and experiments that adapt as they run in Part 58.
Six problems, with full solutions in the README. An exact randomization test by hand; the analysis-of-variance identity; Yates's algorithm on a small factorial; the aliases of a half fraction; the D-optimal design for a straight line; and a sample size. Each takes a page or less. Pause here if you want to try them.
The books and papers this part follows: Fisher's Design of Experiments, Box, Hunter and Hunter, Montgomery, Cochran and Cox, and Kohavi, Tang and Xu, with the papers from Peirce and Jastrow to CUPED.
Thirteen parts of sixty-five, the third of Stage II. We can now design an experiment whose answer has a defensible uncertainty assessment, and analyse it the way it was run. Many examples so far have used measurements. Many of the questions that matter most have yes-or-no answers, or counts. On the evening of the twenty-seventh of January, 1986, engineers and managers discussed whether cold weather would make a rocket's seals fail, using a chart that left out the flights that had no damage. Part 14: counts and categories.
Where it goes next. Permutation tests return in general in Part 16, survey design in Part 18, estimability in the linear model in Part 23 and split plots as mixed models in Part 25; potential outcomes take over randomization in Part 35, and sequential experiments come in Part 58.
Key results
The part's results in one place, for revision.
Try it
Lab 13 · Systematic, randomized, blocked: three layouts on one field
Harvest the field-trial simulator two thousand times under a systematic layout, a completely randomized one and randomized complete blocks, and compare the bias, the spread and the power of each with theory.
python -m videos.stats.labs 13
needs numpy, scipy, matplotlib · download lab13.py ·
source on GitHubtrue difference, variety D minus variety A 3.00
systematic: mean estimate 12.61 (bias +9.61; F test rejects a true null 100% of the time)
randomized: mean, sd of the estimate 2.97, 1.75 (theory 3.00, 1.76)
blocked: mean, sd of the estimate 3.00, 0.89 (theory 3.00, 0.89)
F test at 5%: size under the null randomized 5.6% blocked 4.8%
F test at 5%: power randomized 26% blocked 82%
The systematic layout measures the field, not the varieties. Randomization removes the bias and makes the F test honest; blocking on the gradient takes the gradient out of the error, so the same 48 plots detect the effect far more often.
The code (93 lines; it asserts its own result)
"""Lab 13: lay four varieties out on a field with a fertility gradient three ways, and compare what each design estimates."""
import numpy as np
from videos.coursekit import labs
from explainer.stats.kit import design
TITLE = "Systematic, randomized, blocked: three layouts on one field"
GOAL = ("Harvest the field-trial simulator two thousand times under a systematic layout, a completely randomized "
"one and randomized complete blocks, and compare the bias, the spread and the power of each with theory.")
TASKS = [
"Set gradient=0 and hump=0 in design.Field. What does blocking cost when there is nothing to block on (look at the error df)?",
"Block on rows instead of columns (transpose the layout). Why is that worse than not blocking at all?",
"Replace the columns by a 4 x 4 Latin square repeated three times, analysed with design.latin_anova, and compare the power.",
]
def run(seed=0):
rng = np.random.default_rng(seed)
field = design.Field(rows=4, cols=12, gradient=6.0, hump=4.0, noise=2.0)
fert, sigma = field.fertility, field.noise
k, b, reps = 4, 12, 2000
effect = np.array([0.0, 1.0, 2.0, 3.0]) # variety D (3) yields 3 more than variety A (0)
truth = effect[3] - effect[0]
def systematic(): # varieties in order from west to east, three columns each
return np.repeat(np.arange(k), b // k)[None, :].repeat(k, axis=0)
def crd():
return rng.permutation(np.repeat(np.arange(k), b)).reshape(k, b)
def rcbd(): # every column (a block) holds each variety once, in random order
return np.column_stack([rng.permutation(k) for _ in range(b)])
out = {}
for name, layout in (("systematic", systematic), ("randomized", crd), ("blocked", rcbd)):
est, rej, rej0 = np.empty(reps), 0, 0
for r in range(reps):
lay = layout()
y = field.harvest(effect[lay], rng)
groups = [y[lay == t] for t in range(k)]
est[r] = groups[3].mean() - groups[0].mean()
y0 = field.harvest(np.zeros_like(fert), rng) # the null: no variety differs
if name == "blocked":
by_block = lambda v: np.array([[v[lay[:, j] == t, j][0] for j in range(b)] for t in range(k)]) # noqa: E731
rej += design.rcbd(by_block(y))["p"] < 0.05
rej0 += design.rcbd(by_block(y0))["p"] < 0.05
else:
rej += design.oneway(groups)["p"] < 0.05
rej0 += design.oneway([y0[lay == t] for t in range(k)])["p"] < 0.05
out[name] = dict(est=est, mean=est.mean(), sd=est.std(ddof=1), power=rej / reps, size=rej0 / reps)
# theory: a difference of two group means of 12 plots each, under each randomization
s2_all = fert.var(ddof=1) # the whole field's fertility variance
s2_col = fert.var(axis=0, ddof=1).mean() # the fertility variance left inside a column
sd_crd = np.sqrt((s2_all + sigma ** 2) * 2 / b)
sd_rcbd = np.sqrt((s2_col + sigma ** 2) * 2 / b)
s, c, r = out["systematic"], out["randomized"], out["blocked"]
lab = labs.Lab()
lab.row("true difference, variety D minus variety A", f"{truth:.2f}")
lab.row("systematic: mean estimate", f"{s['mean']:.2f} (bias {s['mean'] - truth:+.2f}; F test rejects a true null {s['size']:.0%} of the time)")
lab.row("randomized: mean, sd of the estimate", f"{c['mean']:.2f}, {c['sd']:.2f} (theory {truth:.2f}, {sd_crd:.2f})")
lab.row("blocked: mean, sd of the estimate", f"{r['mean']:.2f}, {r['sd']:.2f} (theory {truth:.2f}, {sd_rcbd:.2f})")
lab.row("F test at 5%: size under the null", f"randomized {c['size']:.1%} blocked {r['size']:.1%}")
lab.row("F test at 5%: power", f"randomized {c['power']:.0%} blocked {r['power']:.0%}")
lab.note = ("The systematic layout measures the field, not the varieties. Randomization removes the bias and "
"makes the F test honest; blocking on the gradient takes the gradient out of the error, so the same "
"48 plots detect the effect far more often.")
assert s["mean"] - truth > 3 * c["sd"] and s["size"] > 0.9, "the systematic layout is biased by the gradient"
assert abs(c["mean"] - truth) < 5 * sd_crd / np.sqrt(reps) and abs(r["mean"] - truth) < 5 * sd_rcbd / np.sqrt(reps), "unbiased"
assert abs(c["sd"] / sd_crd - 1) < 0.08 and abs(r["sd"] / sd_rcbd - 1) < 0.08, "the randomization variances"
assert abs(c["size"] - 0.05) < 0.02 and abs(r["size"] - 0.05) < 0.02, "both randomized designs hold their level"
assert r["power"] > c["power"] + 0.3, "blocking buys power"
fig, ax = labs.figure(2, size=(11, 4.2), gridspec_kw={"width_ratios": [1, 1.25]})
im = ax[0].imshow(fert, cmap="YlGn", aspect="auto", vmax=fert.max() + 8) # headroom keeps the letters legible
lay = rcbd()
for i in range(k):
for j in range(b):
ax[0].text(j, i, "ABCD"[lay[i, j]], ha="center", va="center", color="#0E1117", fontsize=10, fontweight="bold")
ax[0].set(title="Fertility (hidden) and one blocked layout", xlabel="column = block, west to east", ylabel="row",
xticks=range(b), yticks=range(k))
ax[0].grid(False)
fig.colorbar(im, ax=ax[0], shrink=0.8, label="fertility")
lo, hi = min(c["est"].min(), truth - 1), s["est"].max()
bins = np.linspace(lo, hi, 90)
for name, color in (("systematic", labs.RED), ("randomized", labs.BLUE), ("blocked", labs.GOLD)):
ax[1].hist(out[name]["est"], bins=bins, density=True, color=color, alpha=0.65, label=name)
ax[1].axvline(truth, color=labs.INK, ls="--", lw=1, label="truth")
ax[1].set(title="Estimates of D minus A over 2,000 harvests", xlabel="estimated difference", ylabel="density")
ax[1].legend()
lab.fig = fig
return lab
Now change it
- Set gradient=0 and hump=0 in design.Field. What does blocking cost when there is nothing to block on (look at the error df)?
- Block on rows instead of columns (transpose the layout). Why is that worse than not blocking at all?
- Replace the columns by a 4 x 4 Latin square repeated three times, analysed with design.latin_anova, and compare the power.
Problems, with solutions
Try each problem before opening its solution.
1. An exact randomization test. Six plots, three by lot get a new variety: yields 14, 16, 18 (new) and 10, 11, 15 (old). Find the exact randomization \(p\)-value for the difference in means.
Solution
The six yields total 84. If the new variety's three plots sum to S, the difference in means is (S − (84 − S))/3 = (2S − 84)/3.
The observed S is 14 + 16 + 18 = 48, a difference of 4. |difference| ≥ 4 means S ≥ 48 or S ≤ 36. Of the C(6, 3) = 20 equally likely sets of three:
- only {14, 16, 18} (48) and {15, 16, 18} (49) reach 48;
- by complements, two sets have S ≤ 36.
So p = 4/20 = 0.20. Six plots cannot give strong evidence: the smallest possible two-sided p is 2/20 = 0.10.
2. The ANOVA identity. In a one-way layout, show \(\text{SST} = \text{SSB} + \text{SSW}\): the cross term vanishes.
Solution
Write yᵢⱼ − ȳ = (ȳᵢ − ȳ) + (yᵢⱼ − ȳᵢ) and square. The cross term is 2Σᵢ(ȳᵢ − ȳ)Σⱼ(yᵢⱼ − ȳᵢ). Each inner sum is zero, because deviations from a group's own mean sum to zero. So SST = Σᵢnᵢ(ȳᵢ − ȳ)² + ΣᵢΣⱼ(yᵢⱼ − ȳᵢ)² = SSB + SSW.
3. Yates's algorithm on a 2². A \(2^2\) factorial gives \((1) = 20\), \(a = 30\), \(b = 24\), \(ab = 40\). Find the effects of A, B and AB by Yates's algorithm.
Solution
In standard order the yields are 20, 30, 24, 40.
- Pass 1: sums 50, 64; differences 10, 16.
- Pass 2: sums 114, 26; differences 14, 6.
The column [114, 26, 14, 6] is the total and the contrasts for A, B and AB. Divide the contrasts by 2^(k−1) = 2: A = 13, B = 7, AB = 3. Check A directly: (30 + 40)/2 − (20 + 24)/2 = 35 − 22 = 13.
4. A half fraction of a 2⁵. A \(2^{5-1}\) design has \(E = ABCD\). Give the defining relation, its resolution, and the aliases of \(A\) and \(AB\).
Solution
E = ABCD gives I = ABCDE. The shortest (only) word has five letters, so the design has resolution V.
- A × ABCDE = BCDE, so A is aliased with a four-factor interaction.
- AB × ABCDE = CDE, so AB is aliased with a three-factor interaction.
Main effects and two-factor interactions are all clear of each other.
5. D-optimality for a line. Straight-line regression on \([-1, 1]\): show \(\det M\) is the design's variance of \(x\), and find the D-optimal design.
Solution
With f(x) = (1, x), M = [[1, x̄], [x̄, mean(x²)]] under the design ξ, so det M = mean(x²) − x̄² = Var_ξ(x).
On [−1, 1], Var(x) ≤ mean(x²) ≤ 1, with equality only if every point is at ±1 and x̄ = 0. So the D-optimal design puts half the observations at each end, with det M = 1.
6. A sample size. How many plots per variety detect \(\delta = 2.5\) with \(\sigma = 4\), 80% power, \(\alpha = 0.05\) (normal approximation)?
Solution
n = 2(1.960 + 0.842)² σ²/δ² = 2 × 7.85 × (4/2.5)² = 40.2, so 41 plots per variety. The exact calculation with the noncentral t gives 42, the value in chapter 12.
Notes and sources
Where it comes back
| Idea | Returns in |
|---|---|
| GLMs for counts and binary outcomes | 14, 24 |
| rank and permutation tests in general | 16 |
| survey design: strata and clusters | 18 |
| the linear model in depth, estimability | 23 |
| mixed models: split plots and clustering | 25 |
| the false discovery rate | 33 |
| potential outcomes, interference, two-stage designs | 35, 62 |
| sequential and adaptive experiments | 58 |
| the Coverage Board | every part; 65 |
Sources
- Rothamsted and Fisher.
- R. A. Fisher, "Studies in crop variation I", J. Agric. Sci. 11 (1921); with W. A. Mackenzie, II, J. Agric. Sci. 13 (1923).
- R. A. Fisher, "The arrangement of field experiments", J. Ministry of Agriculture 33 (1926); The Design of Experiments (1935).
- W. B. Mercer & A. D. Hall, J. Agric. Sci. 4 (1911).
- C. S. Peirce & J. Jastrow, Memoirs of the National Academy of Sciences 3 (1884).
- J. Neyman (1923), trans. Statist. Sci. 5 (1990).
- Design and analysis.
- F. Yates, The Design and Analysis of Factorial Experiments (1937); "Incomplete randomized blocks", Ann. Eugenics 7 (1936).
- D. J. Finney, Ann. Eugenics 12 (1945); R. Plackett & J. P. Burman, Biometrika 33 (1946).
- G. Box & K. B. Wilson, JRSS B 13 (1951); G. Box & J. S. Hunter, Technometrics 3 (1961); G. Box & N. Draper, JASA 54 (1959).
- C. Daniel, Technometrics 1 (1959); E. J. Williams, Aust. J. Sci. Res. 2 (1949).
- R. C. Bose, S. S. Shrikhande & E. T. Parker, Canad. J. Math. 12 (1960).
- Multiple comparisons. J. Tukey, "The problem of multiple comparisons" (1953); H. Scheffé, Biometrika 40 (1953); C. Dunnett, JASA 50 (1955).
- Optimal design. K. Smith, Biometrika 12 (1918); J. Kiefer & J. Wolfowitz, Canad. J. Math. 12 (1960).
- Power.
- J. Cohen, J. Abnormal and Social Psychology 65 (1962); Statistical Power Analysis for the Behavioral Sciences (2nd ed., 1988).
- A. Gelman & J. Carlin, Perspectives on Psychological Science 9 (2014).
- Online experiments.
- R. Kohavi, D. Tang & Y. Xu, Trustworthy Online Controlled Experiments (2020).
- A. Deng, Y. Xu, R. Kohavi & T. Walker, WSDM (2013).
- D. Freedman, Adv. Appl. Math. 40 (2008); W. Lin, Ann. Appl. Stat. 7 (2013).
- Textbooks.
- G. Box, J. S. Hunter & W. G. Hunter, Statistics for Experimenters (2nd ed., 2005).
- D. Montgomery, Design and Analysis of Experiments (10th ed., 2019).
- W. Cochran & G. Cox, Experimental Designs (2nd ed., 1957).
- R. Bailey, Design of Comparative Experiments (2008).
About this partfrom its README
Part 13 of a sixty-five-part course in statistics, from a first course to a PhD (see the series plan and the syllabus), in Stage II, Bachelor's: Methods. Part 12 fitted relationships to data that were already there. This part designs the data, to support interpretable comparisons with a defensible uncertainty assessment.
It opens at Rothamsted. Broadbalk has been sown with wheat since 1843, and in 1919 Fisher arrives to analyse seventy-six years of records that can describe but not decide. A simulated uniformity trial shows the soil's own variation, about 8% of the mean. Fisher's answer, in his own words (1926, 1938), is to design the experiment. From there the part covers:
- the three principles on the field-trial simulator: a tidy systematic layout is biased 3.9-fold, randomization makes the estimate unbiased, replication follows σ√(2/n), and pairing halves the SD; Peirce & Jastrow (1884);
- randomization as inference: the sharp null, the exact distribution over all 184,756 labellings, balance of the World's unmeasured heights and incomes, and a doctor who chooses;
- one-way ANOVA as Pythagoras in R²⁴, the F-test, Fisher & Mackenzie's first table (1923), ANOVA as regression, and expected mean squares;
- orthogonal contrasts; the family-wise error of ten pairwise tests; Tukey, Dunnett, Bonferroni and Scheffé multipliers; the HSD grid;
- blocking on a steep gradient (power 74% vs 10%, relative efficiency 15), the RCBD model, Darwin's Zea mays and Fisher's 863 of 32,768, and incomplete blocks;
- Latin squares (Knut Vik, randomized squares, Euler's 36 officers), crossovers and carryover;
- factorials: one-factor-at-a-time on the bakery's diagonal ridge, the 2² square and its interaction, the NPK cube, Yates's algorithm, the interaction plot, Daniel's half-normal plot, hidden replication;
- fractional factorials: the half cube, aliasing and the defining relation, resolution, 2⁷⁻⁴, Plackett–Burman;
- response surfaces on the island bakery: a first-order design, steepest ascent, a central composite design, the fitted quadratic's canonical analysis (Box & Wilson 1951);
- split plots and their two error strata, with the classic mistake on the Board;
- optimal design: the line's end points, Kirstine Smith (1918), D-optimality, thirds at −1, 0, 1, and the Kiefer–Wolfowitz equivalence theorem;
- power, the minimum detectable effect, Cohen's conventions, and the winner's curse (type M and S errors);
- online experiments: Bing's headline, the anatomy of an A/B test, CUPED as regression adjustment, sample-ratio mismatch, the old pitfalls at scale.
Every number on screen is computed in compute.py or inline in a scene:
- the hidden-covariate check uses the World's adults (seed 1662);
- Darwin's differences come from the Museum;
- the field trials run on
statkit.design.Field, and the bakery onstatkit.design.Bakery; - everything else is a seeded simulation.
Built in this part:
-
statkit.design(explainer/stats/kit/design.py):Field, the field-trial simulator: a hidden fertility surface plus plot noise;Bakery, a hidden response surface;- one-way, RCBD and Latin-square ANOVAs;
- random Latin squares;
- 2ᵏ designs, factorial effects and Yates's algorithm;
- fractional factorials and aliases;
- Tukey's HSD and Scheffé's multiplier;
- the D-criterion, the minimum detectable effect, CUPED and the sample-ratio test.
The analyses are checked against SciPy and statsmodels in
tests/test_stats_kit_design.py. -
The field plot (
FieldPlotinexplainer/stats/viz.py): a field from above, painted by fertility or yield, with treatment letters and block frames.
The Coverage Board gains seven rows, all tests at a nominal 5%, R = 10,000:
| Method | Setting | Achieved | Verdict |
|---|---|---|---|
| randomization test | 10 + 10 plots, skewed errors | 5.19% | kept |
| t-test, systematic layout | west vs east, fertility gradient | 100% | broken |
| pairwise t-tests, unadjusted | 5 groups, any of 10 pairs | 26.6% | broken |
| Tukey's HSD | 5 groups, any of 10 pairs | 4.95% | kept |
| split plot analysed as a CRD | whole-plot factor, 4 blocks | 25.6% | broken |
| split plot, whole-plot error | whole-plot factor, 4 blocks | 5.01% | kept |
| CUPED z-test | A/A, 2,000 users | 5.21% | kept |
Chapter notes
| # | Chapter | Numbers |
|---|---|---|
| 0 | Rothamsted, 1919 | uniformity trial: yields 41–60, CV 8% |
| 1 | Three principles | true gain 2: systematic 7.8 (swapped −4.3); 4,000 random layouts mean 1.99, SD 0.71; n = 1 → 6.1, n = 72 → 0.70; pairs SD 0.36 |
| 2 | Randomization as inference | 20 plots: difference 2.71; 6,322 of 184,756 labellings, p = 0.034 (t: 0.031); height-gap SD 1.32 cm, 4.8% beyond 2 SD; a chooser's gap 16.1 cm |
| 3 | One-way ANOVA | SST 107.8 = 46.6 + 61.2; F = 5.07 on (3, 20), p = 0.009; R² = 0.432 |
| 4 | Contrasts | 37.09 + 1.04 + 8.45 = 46.59; FWER 26.6% vs Tukey 4.95%; multipliers t 2.06, Dunnett 2.61, Tukey 2.94, Bonferroni 3.08, Scheffé 3.32; HSD 3.50 |
| 5 | Blocking | first seeded harvest: ignoring blocks F = 0.084, p = 0.968; RCBD F = 1.806, p = 0.189; power 10% vs 74%; MSE 33.4 vs 2.25; Darwin t = 2.15, 863/32,768, p = 0.053 |
| 6 | Latin squares | F = 17.8 vs 0.88 one-way; power 96% vs 20%; 161,280 squares of order 5 |
| 7 | Factorials | OFAT ends at 225 °C, 26.5 min, quality 79.6 vs 85; 2² effects 14.3, 19.0, −15.0; NPK: N 6.21, P 2.95, NP 1.34, SE 0.53 |
| 8 | Fractional factorials | half fraction A 4.21 (full 4.51), AB + CD 1.68; Plackett–Burman XᵀX = 12I |
| 9 | Response surfaces | first-order fit 43.9 + 12.6x₁ + 15.6x₂; best on the path 85.3; stationary point 203.0 °C, 31.7 min, predicted 85.2 (truth 84.9); 29 bakes |
| 10 | Split plots | wrong F = 22.3 on (1, 24), p = 8 × 10⁻⁵; right F = 6.79 on (1, 3), p = 0.08; null rejection 25.6% vs 5.01% |
| 11 | Optimal design | slope SE 0.495σ (even) vs 0.316σ (ends); det M 4/27 = 0.148 vs 0.039; max d(x) = 3 vs 7.5 |
| 12 | Power | n for 80%: 42 (σ = 4) vs 12 (σ = 2); MDE 3.54 at n = 20, 1.77 at n = 80; normal-approximation Cohen 393 / 63 / 25; exaggeration 2.41× at n = 5, 1.12× at n = 42 |
| 13 | Online experiments | ρ = 0.80; SE 0.056 → 0.034; p 0.065 → 3.9 × 10⁻⁵; worth 2.8× the users; SRM 50,000 vs 50,820, p = 0.0098 |
| 14 | Outro | — |
Companion material in this repository
The syllabus's plan for this partfrom SYLLABUS.md, the plan of record
- Hook: Rothamsted (1919). Broadbalk since 1843; Fisher's Studies in Crop Variation (1921).
- Three principles. Replication, randomization, local control; Peirce & Jastrow (1884).
- Randomization as inference. The randomization distribution; balance of hidden covariates (World).
- One-way ANOVA. SST = SSB + SSW as Pythagoras; the F-test; ANOVA as regression.
- Contrasts. Orthogonal contrasts; Tukey's HSD; Scheffé; Dunnett.
- Blocking. Complete blocks; Darwin's Zea mays and Fisher's permutation test (1935).
- Latin squares and crossover designs.
- Factorials. 2^k effects as contrasts; Yates (1937); why one-factor-at-a-time misses a ridge.
- Fractional factorials. Aliasing and resolution (half a cube's corners lit); Plackett–Burman.
- Response surfaces (Box & Wilson 1951). Built: optimizing the World bakery's hidden recipe.
- Split plots. Two error strata and the classic mistake (Board).
- Optimal design, first look. D-optimality; quadratic regression on [−1, 1] puts 1/3 at −1, 0, 1.
- Power and sample size. Cohen's d; the minimum detectable effect.
- Online experiments (Kohavi, Tang & Xu 2020). CUPED (Deng et al. 2013) as regression adjustment; sample-ratio mismatch.
- Outro.
Built: a field-trial simulator; statkit.design.
Build the film
python -m videos.stats.stats13.compute # the part's numbers, into .cache/stats13
python tools/build.py stats13 # render and assemble the film
EXPLAINER_TTS=silent python tools/qa_scene.py stats13 Hook # one chapter, silent, with a contact sheet
Scenes: videos/stats/stats13. Setup: see the course page. Source of these notes: the README and the scenes' narration.
Build it
python -m videos.stats.stats13.compute # once (a few minutes; cached in .cache/stats13)
python tools/build.py stats13 -q l # fast 480p preview
python tools/build.py stats13 # 1080p30 -> renders/stats13.mp4
python tools/qa_scene.py stats13 SplitPlot
python tools/lecture_length.py stats13 --floor 50