Stage II · Bachelor's: Methods
Part 16 of 65Without Assumptions
Can the data stand in for the model when you need a standard error or a p-value?
In 1979 Efron asks for the standard error of a correlation from 15 law schools, r = 0.776, and answers by resampling the 15 schools with replacement: 0.135, against 0.115 from the normal formula. The part first builds the older model-free tools. Permutation tests get exact p-values from exchangeability, and Darwin's maize and the Challenger temperatures carry the sign test, Wilcoxon's signed ranks and Mann-Whitney's count of pairs. Then come the jackknife, the bootstrap's two worlds, and four ways to turn replicates into an interval, each scored on the Coverage Board. The turn is the tank factory: for the maximum of a uniform sample about 63% of resamples repeat the sample's own maximum, and the percentile interval covers 0% of the time. The part ends with two more uses of the data on itself, cross-validation and the kernel density estimate.
What you need. Stage I of this series (sampling distributions and tests, Parts 8 and 10) and the intervals of Part 11.
- Hook
- Efron's law schools, 1979
- Mathematics
- permutation and rank tests, Wilcoxon and Mann–Whitney, the jackknife, the bootstrap, cross-validation
- Built
- statkit.bootstrap, statkit.ranks
What you will be able to do
Bachelor's
- Carry out a permutation test and a bootstrap by hand on a small sample, and say what each assumes.
- Compute the sign, signed-rank and Mann-Whitney statistics and read U/(mn) as the chance that one group's value beats the other's.
Master's
- Derive the exact null distribution of the signed-rank statistic from its generating function.
- Compute jackknife and bootstrap standard errors, and percentile, basic and bootstrap-t intervals, and explain why they differ on skewed data.
PhD
- Show that the bootstrap distribution of a uniform sample's maximum has an atom of mass 1 - (1 - 1/n)^n at the estimate, and explain why m-out-of-n resampling repairs it.
Practice
- Choose between a rank test, a permutation test and a t-test for a given design, and report which hypothesis each one tests.
- Recognise the settings where the ordinary bootstrap fails: extremes, boundaries, infinite variance, dependence and very small samples.
Contents
Each chapter has a home level. Choose a track to see what to read and watch: Bachelor's 33 min · Master's 52 min · PhD 57 min · Practice 44 min.
- 0Fifteen law schools, 1979Bachelor's2 min
- 1Permutation testsBachelor's4 min
- 2The sign test and WilcoxonBachelor's6 min
- 3Mann-WhitneyBachelor's5 min
- 4More rank methodsBachelor's4 min
- 5EfficiencyMaster's5 min
- 6The jackknifeMaster's4 min
- 7The bootstrap principleBachelor's5 min
- 8Bootstrap intervalsPractice6 min
- 9When it failsPhD5 min
- 10Cross-validationPractice4 min
- 11Density estimatesBachelor's4 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.
Fifteen law schools, 1979Bachelor's2 min
In 1979 Bradley Efron, at Stanford, published a paper with a modest title: Bootstrap methods, another look at the jackknife. It became one of the most influential papers in statistics. Every interval since Part 8 leaned on a model for the data: normal, binomial or Poisson, with a formula for the standard error. But what if the statistic has no formula, or the model is doubtful? Efron's idea was to let the data stand in for the population, and simulate.
His running example was fifteen American law schools. For each, the average score of its entering class on the law school admission test, and their average undergraduate grade. The correlation is point seven seven six. How accurate is that, from fifteen schools? What is its standard error?
There is a classical answer: the standard error of a correlation is roughly one minus r squared over the square root of n minus three, point one one five. But that formula assumes the two scores are bivariate normal, which nobody has checked and fifteen points can't confirm. Efron's bootstrap, which we'll build in chapter seven, gives point one three five, assuming independent, identically distributed schools, nonzero variances and suitable finite moments. This part is about methods like that: answers that lean on the data rather than on a model.
The name is a joke: to pull oneself up by one's own bootstraps, an impossible feat attributed to Baron Munchausen. The bootstrap seems to get something from nothing: a whole sampling distribution from a single sample. We'll see why it works, and when it doesn't. The part also covers an older family of methods built on ranks, which give exact tests under exchangeability or symmetry, without a normal model: Frank Wilcoxon's of 1945, Henry Mann and Donald Whitney's of 1947. Both families rest on the same idea: use the symmetries the data themselves possess.
Numbers: r = 0.776; SE 0.115 (normal formula), 0.135 (bootstrap)
1Permutation testsBachelor's4 min
Part 10's permutation machine and Part 13's randomization test return, now as a general principle. Suppose the null hypothesis is that two samples come from the same distribution, whatever it is: not normal, not anything in particular. Then the pooled observations are exchangeable, Part 5's idea: their joint distribution doesn't care about the order. So every way of splitting them into a group of m and a group of n is equally likely. The p-value is the share of splits whose statistic is at least as extreme as the observed one. It's exact, for any statistic and any distribution. In an experiment the justification is the randomization, as in Part 13; in observational data, it's exchangeability under the null.
Here are twelve men's and twelve women's incomes from the World, in thousands: skewed, as incomes are, with a few large values. A t-test's normal theory is shaky with samples this small and this skewed. The women's mean is twenty thousand higher. Shuffle the labels: each shuffle is a split the null hypothesis says was just as likely. Again, and again.
There are two million seven hundred thousand ways to split twenty-four incomes into two groups of twelve, few enough for a computer to try every one. Here is the exact distribution of the difference in means under the null. A difference as large as twenty thousand, either way, happens in twenty-three percent of the splits: p equals point two three. Welch's test, Part 10's, gives point two four: the normal approximation is decent even here. The World generates income without a direct sex effect, but its finite population has a small realized difference. The permutation null requires exchangeable groups, not merely equal means.
The statistic can be anything that measures a difference: the difference in means, in medians, in trimmed means. It must be chosen before looking, or the exactness is lost. When there are too many splits to count, sample ten thousand at random; adding one to the count and to the total keeps the test valid, as in Part 10. Every choice gives an exact test. What the choice changes is the power: a statistic that resists outliers detects shifts in heavy-tailed data far better, which is where ranks come in.
Permutations test association too. If LSAT and GPA were independent across law schools, pairing each school's LSAT with a random school's GPA would be as likely as the real pairing. Shuffle the GPA column twenty thousand times and recompute the correlation each time. A correlation as large as point seven seven six turns up in fewer than two shuffles in a thousand. This is evidence against independence under IID sampling, without a normality assumption. The Monte Carlo p-value includes the observed pairing.
The limits. The null hypothesis must make the observations exchangeable. "Same mean, but perhaps different spreads" doesn't: shuffling then tests whether the distributions are identical, a different question. Data that depend on each other, in time or in clusters, generally need permutations that respect their dependence: Part 17. Some dependent laws are exchangeable. Permutation tests can also be inverted for confidence sets. For standard errors and another approach to intervals, we turn to the bootstrap.
Numbers: 12 + 12 incomes, difference −20.4; 2,704,156 splits, p = 0.232; Welch 0.237; law schools p ≈ 0.0017
2The sign test and WilcoxonBachelor's6 min
Signs and signed ranks. In 1876 Charles Darwin published an experiment on maize. In each of fifteen pairs, one plant came from a cross-fertilized seed and one from a self-fertilized seed, grown in the same pot. Here are the differences in final height, crossed minus self, in eighths of an inch, as Fisher reprinted them in 1935. Thirteen of the fifteen are positive. The mean difference is about twenty-one, with a standard deviation near thirty-eight. And two pairs go strongly the other way. Darwin asked his cousin Francis Galton to analyse the numbers; the data have been a test case ever since. Is cross-fertilization better? We'll ask three tests, each making fewer assumptions than a t-test.
The oldest test of all is the sign test; John Arbuthnot used it in 1710 on London's christening records. For independent continuous differences with median zero, each sign is equally likely positive or negative. So the number of positive signs is Binomial fifteen, one half, whatever the shape of the distribution. Thirteen or more positives, or two or fewer, has probability point oh oh seven four. The sign test uses only the signs, so it assumes nothing about the distribution, not even that it's symmetric. The price is that it throws away the sizes: it doesn't notice that the two negative differences are large.
Fisher's analysis in The Design of Experiments was one of the first permutation tests in print. If crossing does nothing, and the two plants in a pair were allotted at random, then which plant is the taller is a coin toss. Alternatively, independent symmetric null differences justify the sign flips. Darwin's historical allocation should not simply be assumed random. So keep the sizes, flip the signs. Here's one flipped copy, and another, and another. There are two to the fifteen, thirty-two thousand seven hundred and sixty-eight sign patterns. The observed differences sum to three hundred and fourteen. Of all the patterns, one thousand seven hundred and twenty-six give a sum at least that far from zero. p equals point oh five three. Fisher counted them, and found the answer agreed closely with the t-test, which was his point: here the normal theory is a good approximation to an exact argument that needs no normality.
In 1945 Frank Wilcoxon, a chemist at American Cyanamid, proposed a compromise between using signs and using sizes. Sort the absolute differences and replace each by its rank, one to fifteen, keeping its sign. The two negative differences, sixty-seven and forty-eight, have ranks fourteen and ten. The signed-rank statistic W-plus is the sum of the ranks of the positive differences: one hundred and twenty, the total of all fifteen ranks, minus twenty-four, which is ninety-six. The assumptions here are independent continuous differences symmetric about zero, with distinct nonzero absolute values, stronger than the sign test's, weaker than normality. Ranks keep the ordering of the sizes and discard the rest, so one wild value can't dominate.
Under the null, rank k carries a plus sign with probability one half, independently. So W-plus is a sum of independent terms, each zero or k with equal chance. Its distribution is read off a generating function: the product over k of one plus x to the k, over two. The probability that W-plus equals w is the coefficient of x to the w: the share of the thirty-two thousand sign patterns whose positive ranks sum to w. Multiply out the polynomial and you have the whole distribution: symmetric about sixty, and nearly normal already. Ninety-six or more, or twenty-four or fewer: p equals point oh four one. And this table doesn't depend on the distribution of the differences, only on their being symmetric. One table serves every problem. That's why rank tests spread before computers did: Wilcoxon's paper came with tables you could carry.
Side by side. The sign test, using only signs: point oh oh seven. Wilcoxon's, using signs and ranks: point oh four one. Fisher's flip, using the sizes themselves: point oh five three. And the paired t-test, assuming normality: point oh five oh. These aren't four estimates of one true p-value. They're exact answers, or in the t-test's case an approximate one, to slightly different questions, each with its own assumptions. The sign test gives the smallest p here, because it's blind to the thing that worries the others: the two negative differences are large. Choose the test before looking, for the assumptions you're willing to make, and never shop among them for the smallest p.
A test answers yes or no; we'd like an estimate too. Joseph Hodges and Erich Lehmann found the one that goes with Wilcoxon's test, in 1963. Average every pair of differences, including each with itself: one hundred and twenty Walsh averages. W-plus is the number of them that are positive. The Hodges–Lehmann estimate of the shift is their median, twenty-five. Inverting the test gives an interval: the shifts that Wilcoxon's test wouldn't reject are those between the twenty-sixth and ninety-fifth Walsh averages, four to forty-one and a half, with confidence ninety-five point two percent, exactly, for any symmetric distribution. The t-interval is nearly the same here. The rank methods give up very little when the data are well behaved, a point we'll make precise in chapter five.
Numbers: 13 of 15 positive, sign p = 0.0074; Fisher 1,726/32,768 = 0.053; W⁺ = 96, p = 0.041; t p = 0.050; Hodges–Lehmann 25, 95.2% CI [4.0, 41.5]
3Mann-WhitneyBachelor's5 min
Part 14's twenty-three shuttle flights before Challenger return. Sixteen had no O-ring distress, seven had some. Here are their launch temperatures. The samples are small, the temperatures aren't normal, and several are tied. Part 14 fitted a logistic regression. Here's a question that needs no normal model: are the distress flights colder, in the sense that a random distress flight tends to be colder than a random undistressed one?
Pool all twenty-three temperatures, sort them, and rank them from one to twenty-three. Tied temperatures share the average of their ranks: the four flights at seventy degrees occupy ranks eleven to fourteen, so each gets twelve and a half. Wilcoxon's rank-sum statistic adds up the ranks of one group. The distress flights' ranks sum to fifty-two and a half, low, because they sit at the cold end. Henry Mann and Donald Whitney, at Ohio State in 1947, subtracted the smallest possible value, seven times eight over two, giving U equals twenty-four and a half, and worked out its distribution. It's the same test, under two names, and it's called the Wilcoxon–Mann–Whitney test to be fair to both. The ties need care: with them we recompute the exact conditional law from the pooled midranks rather than use an untied table.
Mann and Whitney's form has a direct meaning. Pair every undistressed flight with every distress flight: sixteen times seven, a hundred and twelve pairs. Colour a pair blue when the undistressed flight was the warmer, grey for a tie, counted as a half. The number of blue cells, plus half the grey, is the U statistic for the undistressed group: eighty-seven and a half. It's a hundred and twelve minus the twenty-four and a half we found from the ranks. Counting pairs and summing ranks are the same calculation.
The null hypothesis is that temperature and distress are unrelated: all twenty-three temperatures exchangeable, so any seven of them were equally likely to be the distress flights. It's chapter one's permutation test, applied to ranks. With ties, the conditional null depends on these pooled midranks. A subset-sum recursion counts all 245,157 assignments: here it is, centred at fifty-six; ties need not leave the distribution symmetric. A U as far from fifty-six as eighty-seven and a half: the exact two-sided p-value, point oh three three five, includes all assignments at least this far from the null mean. The tie-corrected normal approximation is about point oh three eight. Both give evidence of association in these flights under the exchangeability null.
Divide U by the number of pairs: point seven eight one. That estimates the probability that a random undistressed flight was warmer than a random distress flight, counting ties as half. It's also a number from Part 14: the area under the ROC curve, if temperature is used as a score to separate the two kinds of flight. The Mann–Whitney statistic and the AUC are the same thing; David Bamber pointed that out in 1975. The statistic estimates that probability with half credit for ties. The usual exact test assumes equal distributions; AUC equal to one half alone is a weaker null and needs different calibration.
A warning about what's tested. If the two distributions have the same shape and differ only by a shift, the test compares medians, or any other location, and the Hodges–Lehmann median of the pairwise differences estimates the shift. Without that shape assumption, U estimates the AUC, but its usual permutation calibration still assumes identical distributions. The two symmetric normal distributions pictured have the same median and AUC one half despite different spreads, yet the test, calibrated for identical distributions, rejects them seven percent of the time with twenty in each group, and with unequal group sizes it can be off in either direction: the rank version of the Behrens–Fisher problem from Part 10. Ranks free us from normality, not from thinking about what the null hypothesis says.
Numbers: rank sum 52.5, U = 87.5 of 112, conditional exact p = 0.03352 (0.03757 tie-corrected normal approximation); AUC 0.781
4More rank methodsBachelor's4 min
Ranks extend to more than two groups. Here are ten incomes from each of three regions of the World. Incomes are skewed, and one in region three is a hundred and seventy-seven thousand, which inflates that group's variance and the ANOVA's error term. Part 13's one-way analysis of variance gives F equals point three six, p equals point seven oh. What would a test that ignores the sizes say?
Rank all thirty incomes together. The hundred and seventy-seven thousand becomes rank thirty, no more extreme than any other top value. William Kruskal and Allen Wallis, in 1952, did a one-way analysis of variance on the ranks: the statistic H measures how far each group's mean rank strays from the overall mean rank, N plus one over two. Here H is one point five three; the mean ranks are fourteen point three, thirteen point nine and eighteen point three, around the fifteen and a half expected. Under the null H is approximately chi-squared with two degrees of freedom, so p equals point four seven, or exactly, by permuting the ranks. With two groups, Kruskal–Wallis is the Wilcoxon–Mann–Whitney test.
For Part 13's randomized blocks there's a rank test too. Rank the treatments within each block, here four treatments in five blocks, so whatever makes one block better than another drops out: only the order inside a block counts. Milton Friedman, the economist, proposed the statistic in 1937, as a young statistician: it compares the treatments' rank sums with what chance would give. For these ranks Q is ten point two. The chi-squared approximation gives p about point oh two, but five blocks is small: exact within-block permutations are preferable under independent exchangeable blocks. With two treatments it ranks outcomes like a sign test, but its chi-squared p-value is only an approximation to the exact sign-test tail.
Ranks measure association too. Take the fifteen law schools and replace each LSAT and each GPA by its rank among the fifteen. Charles Spearman's correlation, from 1904, is Pearson's correlation computed on the ranks. Pearson's r is point seven seven six; Spearman's is point seven nine six. Because ranks don't change when you take logs, square roots, or any strictly increasing transformation, neither does Spearman's correlation. It measures how monotone the relationship is, not how straight.
Maurice Kendall's tau, from 1938, counts pairs, like Mann and Whitney. Take every pair of schools and ask whether LSAT and GPA put them in the same order. Green pairs agree, concordant; red pairs disagree, discordant. Of the hundred and five pairs, eighty-six are concordant and nineteen discordant. Tau is the difference as a share of all pairs: point six three eight. Its meaning is direct: one plus tau over two, point eight two, is the chance that a random pair of schools is ordered the same way by both scores. Tau is smaller than Spearman's correlation, as it usually is, but it's on a different scale, not a weaker finding.
Why prefer ranks? Suppose one school's GPA had been mis-recorded: the school with the lowest LSAT entered as four point two. Pearson's correlation collapses from point seven seven six to point one five. Spearman's falls to point four four and Kendall's to point three nine. One wrong value still hurts the rank correlations, but less, because a point's rank can move only so far, while its value can move without limit. That's robustness: a bounded influence for every observation. We'll measure it properly in Part 30, with the influence function.
Numbers: H = 1.53, p = 0.47 (F = 0.36, p = 0.70); Friedman Q = 10.2; Spearman 0.796, Kendall 0.638 (86 vs 19 pairs); one bad GPA: 0.148, 0.436, 0.390
5EfficiencyMaster's5 min
Ranks throw away the sizes of the observations. Surely that costs power, and if the data really are normal, the t-test should be much better? Edwin Pitman, in Australia, gave the measure in lecture notes of 1948: the asymptotic relative efficiency, the limiting ratio of the sample sizes two tests need for the same power against small shifts. For Wilcoxon against t it has a closed form, twelve sigma squared times the squared integral of the density squared. We'll prove it in Part 30. At the normal distribution, where the t-test is optimal, it's three over pi: point nine five five. Using ranks on normal data costs four and a half percent of the sample: a hundred observations analysed by ranks are worth ninety-five and a half analysed by t. That's a surprisingly small price.
Now a simulation, with three error distributions. The normal. Student's t with three degrees of freedom, rescaled to variance one: taller in the middle, with heavy tails. And a contaminated normal: ninety percent of observations are standard normal, ten percent come from a normal with standard deviation five. Its density is barely distinguishable from the normal in the middle; the difference is one value in ten being a gross error. John Tukey made this model famous in 1960 as the realistic case: most measurements are good, a few are wild.
Two groups of twenty, the second shifted by point eight, four thousand trials of each test. At the normal, the t-test detects the shift sixty-nine percent of the time, Wilcoxon–Mann–Whitney sixty-six: a small loss, as Pitman said. With t-three errors, the rank test is ahead, eighty-nine percent to seventy-seven. Under contamination it's not close: fifty-two percent against thirty-five. The wild values inflate the standard deviation in the t statistic's denominator and hide the shift; ranks barely notice them.
Pitman's formula applies to regular continuous location families with finite variance and square-integrable density. At the normal, point nine five five. At the logistic, one point one: the rank test is already better. At the double exponential, one and a half. At t-three, one point nine: the t-test needs almost twice the sample. At our contaminated normal, two point four. In 1956 Joseph Hodges and Erich Lehmann proved the striking result: over this class of regular continuous distributions, the efficiency is never below a hundred and eight over a hundred and twenty-five, point eight six four. And it has no upper limit: with heavy enough tails, the t-test can be arbitrarily worse. The bound is a 13.6 percent information loss, or at most about 15.7 percent more observations for equal local power. With unlimited efficiency gain possible, the rank test is a very cheap insurance policy.
What about validity? The Coverage Board's first two rows for this part are about size, not power. With no shift at all, under contamination, twenty and twenty, ten thousand trials: the t-test rejects four point four percent of the time: kept, slightly conservative. This particular simulation is mildly conservative; twenty observations do not guarantee a reliable normal approximation for all heavy tails. Wilcoxon–Mann–Whitney: five point two percent, kept here with the asymptotic rank-test calibration. Exact permutation calibration instead controls size by exchangeability. The t-test keeps size in this simulation. It's weak: the price of heavy tails is paid in power, which the Board doesn't show and the last chart did.
So: rank tests cost little when the data are normal, and can gain a great deal when they aren't. Both kinds of test keep their size in these examples: the difference is power. The catch is the question asked. A rank test is about whether one distribution tends to exceed the other, not about the difference in means, which is often the quantity a decision needs, such as total income or total cost. For estimates and intervals of whatever quantity you care about, without a model, we turn to resampling: first the jackknife, then the bootstrap.
Numbers: power t / WMW: 0.69 / 0.66 (normal), 0.77 / 0.89 (t₃), 0.35 / 0.52 (contaminated); ARE 0.955, 1.097, 1.5, 1.90, 2.41; bound 0.864
6The jackknifeMaster's4 min
Before the bootstrap there was the jackknife. Maurice Quenouille, in 1949, proposed it to reduce bias; John Tukey, in 1958, saw it could estimate a standard error, and gave it its name, for a rough all-purpose tool you keep in your pocket. The recipe: leave out one school, recompute the correlation from the other fourteen, put the school back, and leave out the next. Fifteen recomputations, fifteen values. They scatter around point seven seven six. How much they move tells us how sensitive the correlation is to the data.
Average the leave-one-out values. Quenouille's bias estimate is n minus one times the difference between that average and the full-sample correlation: minus point oh oh six five, tiny here. For estimators with a smooth bias expansion, it removes the leading one-over-n term. Tukey's standard error looks like the standard error of the mean of the fifteen leave-one-out values, multiplied by n minus one. That's because the leave-one-out values are far too alike: any two share thirteen of their fourteen schools, so their spread must be scaled up. The result is point one four three, with no model at all: larger than the normal-theory formula's point one one five, and close to the bootstrap's point one three five.
A check that the bias correction does what it claims. Take the plug-in variance of the fifteen LSAT scores, dividing by n. Part 9 showed its bias is exactly minus sigma squared over n, a pure one-over-n term. Subtract the jackknife's estimate of the bias: the result is exactly s squared, the variance with n minus one. The jackknife rediscovers Bessel's correction by itself, from the data, with no algebra.
The jackknife has a second use. Scale each school's change by n minus one, and you have a measure of how hard that school pulls on the estimate: a finite-sample version of what Part 30 will call the influence function. Draw each school with its marker area above a fixed baseline proportional to its absolute pull. Red schools lower the correlation, blue ones raise it. One school dominates: LSAT five seven six, GPA three point three nine, far above the trend. Without it the correlation is point eight nine three. It's Part 12's influence probe, extended to any statistic: not only regression coefficients but correlations, ratios, medians.
But the jackknife has a blind spot. Leave one LSAT out at a time and take the median of the other fourteen: there are only three distinct answers. The median of fourteen is the average of the middle two, and leaving out one point can only shift which two those are. The jackknife standard error is fourteen point seven; the bootstrap, which we're about to build, gives eighteen point four. The jackknife works by small perturbations, so it needs a statistic that changes smoothly with the data, and the median jumps. Efron showed in 1982 that for the median the jackknife standard error fails relative consistency: after multiplication by the square root of n it remains noisy. The unscaled error estimate still shrinks. Something that perturbs the data more boldly is needed.
Numbers: bias −0.0065, SE 0.143; without school 1, r = 0.893; LSAT median: 3 distinct values, SE 14.7 vs 18.4
7The bootstrap principleBachelor's5 min
Here is the bootstrap as a machine: the fifteen law schools as tokens. Draw a school at random, copy it down, put it back, and draw again, fifteen times. Some schools are copied twice or three times, some not at all. That's a resample: a new dataset of the same size, drawn with replacement from the sample. Compute its correlation, and drop it on the line. Clear, and resample again. Each resample is a dataset the population might plausibly have given us, if the population looked like the sample. Again. And again.
Do it two thousand times. The computer takes a fraction of a second. The bootstrap standard error is just the standard deviation of the two thousand resampled correlations: point one three five. The histogram is skewed to the left, because a correlation can't exceed one: the sampling distribution isn't normal, and the bootstrap shows it. The normal-theory formula said point one one five, the jackknife point one four three. Efron's paper used exactly this example, and found the same thing: a standard error for a statistic with no formula, or with a formula we don't trust, by brute force.
Efron's diagram makes the logic plain. In the real world, an unknown distribution F produces our sample, and the sample produces the estimate. If we could repeat that, we'd see the estimate's sampling distribution, but we get one sample. So build a stand-in for F from the sample: the empirical distribution, F-hat, which puts mass one over n on each observation. In the bootstrap world F-hat plays the part of the population. Sampling from it, with replacement, is resampling; and there we can repeat as often as we like. We want the distribution of the estimate's error under F, which we can't see. We can compute the distribution of the resampled estimate's error under F-hat. The bootstrap is the plug-in principle, Part 9's idea, applied to a whole sampling distribution: use the second as an estimate of the first. Part 30 will show when that's justified.
Can we check the principle? In the World, yes, because we can draw as many real samples as we like. The statistic is the median income, from samples of twenty-five. On the left, the real sampling distribution, two thousand samples from the World, centred on the true median of thirty-nine thousand. On the right, the bootstrap from a separate fixed sample, whose median is thirty-seven point seven. The real standard deviation is six point oh six; the bootstrap's, four point seven two. In the right ballpark, from one sample, but low. And the bootstrap histogram is spiky: the median of a resample can be any of the 25 sample values. These 2,000 replicates happen to visit sixteen of them. With a median and twenty-five observations, the bootstrap is rough. For smooth statistics like means and correlations it does much better.
How many resamples? Fifteen schools can be drawn in fifteen to the fifteenth ordered ways; as unordered collections, there are seventy-seven million distinct resamples. The ideal bootstrap would average uniformly over ordered draws, or give unordered multisets their multinomial weights. They are not equally likely. Instead we sample B of them: Part 7's Monte Carlo, with error shrinking like one over root B. There are now two errors: the sampling error, from having one sample, which no amount of computing removes; and the Monte Carlo error, from finite B, which we can make as small as we like. For a regular distribution with finite fourth moments, a thousand resamples can give a standard error to within a few percent. Interval endpoints sit in the tails, where draws are scarce, and need a few thousand.
What does the bootstrap assume? That the observations are independent draws from one distribution: you must resample in the way the data were sampled. Pairs stay pairs, as the law schools' LSAT and GPA did; clusters are resampled as clusters; time series need blocks, which is Part 17. That the empirical distribution is close to the real one, which needs a reasonable sample. And that the statistic depends smoothly on the distribution. Means and correlations do. A maximum doesn't, and chapter nine shows what happens then. What it doesn't assume is the gift: no normality, and no formula for the standard error.
Numbers: SE 0.135; median income: truth 38.9, sample 37.65, SD 6.06 real vs 4.72 bootstrap; 77,558,760 distinct resamples
8Bootstrap intervalsPractice6 min
We have two thousand bootstrap correlations. How do we make an interval? The simplest answer, Efron's first: take the middle ninety-five percent of the replicates, from the two and a half to the ninety-seven and a half percentile. Point four four seven to point nine six two. It has nice properties. It can't leave the range of possible values, and if you transform the statistic, say by Fisher's z, ideal percentile endpoints transform with it. Finite Monte Carlo interpolation introduces small discrepancies. One useful sufficient motivation is that a transformation makes the estimate approximately unbiased and normal with constant variance. This is not a necessary condition. When the estimate is biased or its spread changes with the parameter, the percentile interval is off.
The bootstrap principle suggests something different. It says the error of a replicate about the estimate mimics the error of the estimate about the truth. So the error lies between the replicates' quantiles minus the estimate, with probability ninety-five percent. Solve for theta: the interval is twice the estimate minus the upper quantile, to twice the estimate minus the lower one. It's the percentile interval reflected about the estimate: where the replicates have a long left tail, this interval has a long right one. For the law schools: point five nine one to one point one oh six. Its upper end is a correlation above one, which is impossible. The basic interval is right in logic, and here the reflection takes it out of bounds: it's only as good as the approximation that the error's distribution doesn't depend on theta.
A third idea goes back to Part 8's pivot. Studentize each replicate: subtract the sample mean and divide by the replicate's own standard error. The quantiles of these t-star values replace Student's table. Gosset's table assumed normal data; this one is built from the data themselves, and so it can be asymmetric. Try it on fifteen incomes from the World, which are very skewed. The mean is forty-two point four; the World's true mean is forty-nine point five. Student's t-interval is symmetric: twenty-eight to fifty-seven. The percentile interval is narrower: thirty-one to fifty-five. Both catch the truth this time, but both sit nearly symmetrically around a mean that's too low. The bootstrap-t interval stretches to the right, thirty to sixty-two, because with a right-skewed population a low sample mean usually comes with a low standard deviation too. Peter Hall showed in 1988 that this interval is accurate to second order under suitable smoothness and moment conditions: its coverage error shrinks like one over n rather than one over root n.
Efron's answer to the percentile interval's flaws, in 1987, was BCa: bias-corrected and accelerated. It's stated here, not derived. The bias correction z-nought measures how far the replicates are off-centre: only forty-four and a half percent fall below the observed correlation, so z-nought is minus point one three seven. The acceleration a measures how fast the standard error changes with the parameter, estimated from the skewness of the jackknife values of chapter six: minus point oh seven six. Together they move the percentile levels: instead of two and a half and ninety-seven and a half, BCa uses the point four and the ninety-two point nine percentiles. For the law schools, point two eight seven to point nine four three: shifted down, and much longer on the left. BCa keeps the percentile interval's good properties, staying in range and transforming correctly, and it's second-order accurate like the bootstrap-t.
Side by side, for the fifteen law schools. The normal-theory interval, through Fisher's z: point four four to point nine two. The estimate plus or minus one point nine six bootstrap standard errors: it crosses one. The percentile interval. The basic interval, crossing one. And BCa, reaching down to point two nine. Five reasonable recipes, five different answers, from fifteen points. The disagreement is itself informative: with a sample this small and a bounded, skewed statistic, the data can't pin down the interval's shape. Which recipe can we trust? That's a question for the Board.
The Board's test: the mean of fifteen incomes from the World, whose distribution is extremely skewed, ten thousand samples, nine hundred and ninety-nine resamples each. The percentile interval covers eighty-five and a half percent: broken. BCa, eighty-six point seven: broken too, barely better. The bootstrap-t, ninety-one point six: still broken, but the best by far. And Student's t, the method that assumes normality: eighty-eight point four. Between the percentile and the bootstrap-t. With fifteen observations from a population this skewed, none of these four recipes reaches ninety-five percent. The bootstrap is not magic: it can't conjure the incomes in the long right tail that the sample didn't happen to contain.
The percentile interval is simple and stays in range, but its coverage error shrinks slowly and small-sample coverage can be poor in either direction. The basic interval has the right logic but can leave the parameter space. Under stronger smoothness and moment conditions, the bootstrap-t is second-order accurate but needs a standard error for every resample, which for complicated statistics means a bootstrap inside the bootstrap. BCa is second-order accurate under suitable regularity, stays in range, and is a common software option. Its finite-sample fitted acceleration need not transform exactly. And none of them can see what the sample didn't contain.
Numbers: percentile [0.447, 0.962], basic [0.591, 1.106], normal [0.513, 1.040], BCa [0.287, 0.943], Fisher z [0.439, 0.922]; incomes: t [28.0, 56.9], percentile [30.7, 55.5], bootstrap-t [30.2, 61.7], truth 49.5
9When it failsPhD5 min
Chapter eight's failure was gentle: intervals a little too short. Here's a case where the bootstrap fails completely, and it's one we know well. Part 9's tank factory, in its continuous form: fifty draws from a uniform distribution on zero to theta, with theta equal to one. The natural estimate is the maximum, here point nine six six. Its sampling distribution has a simple formula, and it's continuous: the maximum is always a little below theta, by a random amount. Scaled by n, the shortfall is approximately exponential. The maximum is unusually accurate, with an error of order one over n, and it isn't a smooth function of the data's distribution: it depends only on the edge.
On the left, the real sampling distribution of the maximum: four thousand samples of fifty. It's smooth, piled up just below one. On the right, four thousand resamples of our one sample. The maximum of a resample can only be one of the sample's values, and usually it's the largest. Sixty-two and a half percent of the resamples have exactly the original maximum. The bootstrap distribution is a few spikes; the real one has no spike at all. The bootstrap world doesn't resemble the real one, so the ordinary uncorrected bootstrap intervals can fail.
Why sixty-two percent? A resample's maximum is below the sample's only if the largest value is never drawn. Each of the n draws misses it with probability one minus one over n, so all of them miss with probability that to the n-th power. The chance of a spike is one minus that: point six three six for fifty, against the simulated point six two five. And as n grows it tends to one minus one over e, the limit from Part 6. The spike never goes away, however large the sample: the bootstrap is inconsistent for the n-scaled limiting law of the maximum, although the maximum itself is point-consistent. Bickel and Freedman, in 1981, were among the first to say exactly when the bootstrap works; the maximum is a standard counterexample.
The Coverage Board. Ten thousand samples of fifty from the uniform, with theta equal to one. The percentile interval covers zero percent. Not low: zero. Every resampled maximum is at most the sample maximum, which is below theta, so the interval always lies entirely below the truth. The basic interval, which reflects the percentiles above the estimate, does better, eighty-seven point eight percent, but it's still broken: the spike puts too little spread above the maximum.
How to fix it. When there's a model, use it, with a pivot in Part 11's sense: the maximum over theta has a Beta n, one distribution, whatever theta is. That gives an exact interval, from the maximum to the maximum over point oh five to the one over n: about point nine six six to one point oh two six. It covers exactly ninety-five percent in this continuous IID uniform model. Or a parametric bootstrap: resample from the fitted uniform, not from the data, and invert the quantiles of maximum-star over the fitted maximum. A raw percentile interval still fails. And without a model, resample fewer points than you have, m out of n, and rescale. Take m tending to infinity but m over n tending to zero. Use m times the bootstrap maximum gap to approximate n times the true gap; the spike then shrinks; Peter Bickel, Friedrich Götze and Willem van Zwet showed in 1997 that this repairs many failures, at a cost in efficiency.
The maximum isn't the only failure. Edges in general: maxima, minima, and parameters at the boundary of the space, such as a variance component that might be zero. Heavy tails with infinite variance, where the sample mean has no normal limit and the bootstrap of the mean is inconsistent. Dependent data, where resampling single points destroys exactly what matters; Part 17 resamples blocks instead. And tiny samples, where the empirical distribution is a poor copy of the population. The bootstrap's success is a theorem, and like every theorem it has conditions: smoothness and independence. Within them it's one of the most useful tools in statistics; outside, it fails without warning, which is why the Board tests it.
Numbers: P*(spike) 0.625 (theory 0.636, limit 0.632); exact one-sided 95% CI [0.966, 1.026]
10Cross-validationPractice4 min
The bootstrap and jackknife resample to measure uncertainty. Cross-validation holds data out to measure prediction. Two hundred adults from the World: log income against age. A straight line. A cubic, which rises and then flattens, as incomes do over a career. A polynomial of degree eight, which wiggles at the ends where data are thin. The higher the degree, the smaller the training error: a more flexible curve always fits the points it was fitted to at least as well. But which will predict the incomes of new people best?
Cross-validation answers by pretending some of the data are new. Split the data at random into ten folds. Hold out the first fold, fit the curve to the other nine, and predict the held-out points. Then the second fold, and so on, so that every observation is predicted exactly once, by a fit that never saw it. The average squared error of those predictions estimates how well the method predicts new data. Mervyn Stone and Seymour Geisser set out the idea in 1974 and 1975; it's the jackknife's leave-out logic, aimed at prediction.
Here are the two errors for polynomials of degree one to eight. The training error falls every time the degree goes up. The cross-validated error falls at first, while the curve learns the real shape of the career, then rises, as the extra flexibility fits noise that new people won't share. It's smallest at degree three. The differences are small, so the cross-validation was repeated over five random splits into folds and averaged: CV has its own randomness, which a single split can mislead you with.
Why does the training error mislead? For a fixed full-rank linear model with homoskedastic errors, compare fresh responses at the same design: on average the training error is too small by two sigma squared p over n, where p is the number of coefficients. Colin Mallows built his C-p criterion on it in 1973, and Part 19 will derive it. The cubic's residuals give sigma squared about point three three. For the cubic, four coefficients: training error plus the optimism is point three three nine, near the cross-validated point three four two. For degree eight, nine coefficients: point three four nine against cross-validation's point three five four. Cross-validation finds the optimism by brute force, with no formula, and so it works where no formula exists: trees, neural networks, anything that predicts.
With as many folds as observations, cross-validation is leave-one-out: the jackknife's scheme. For least squares, when every deleted design has full rank and leverage is below one, it needs no refitting. The prediction error for a point left out is its ordinary residual divided by one minus its leverage, Part 12's h-i-i: high-leverage points pull the fit towards themselves, so their residuals understate their prediction errors. The whole leave-one-out error comes from one fit. David Allen called it PRESS, the prediction sum of squares, in 1974. In general, though, five or ten folds are the usual choice: fits on ninety percent of the data can differ from fits on all the data. The bias and variance trade-off depends on the learning method and data; fewer folds are cheaper, not universally less variable.
Some cautions. Cross-validation estimates how well a procedure performs on data like these, not the error of the one fitted curve. If you try many models and report the smallest cross-validated error, that minimum is optimistic, the selection problem from Part 10 once more. To report honestly, the choosing must happen inside each fold: nested cross-validation. And the folds must respect the data's structure, as the bootstrap's resamples must: hold out whole clusters, or blocks of time, never single points from them. Part 19 takes prediction and model choice up in full.
Numbers: best degree 3, CV 0.3425; optimism: 0.3395 vs CV 0.3425 (degree 3), 0.3493 vs 0.3536 (degree 8)
11Density estimatesBachelor's4 min
Everything in this part has avoided assuming a shape for the distribution. The last chapter estimates the shape itself. Here are sixty heights from the World, as a histogram with ten-centimetre bins. And here are the same sixty heights, with the same bin width, the bins just shifted by five centimetres. The peak has moved, and its shape has changed. A histogram depends on an arbitrary choice of where the bins start, and it's a staircase, where a smooth density may be a useful approximation.
Murray Rosenblatt in 1956, and Emanuel Parzen in 1962, proposed the fix. Mark each observation on the axis. Over each one, put a small bump: a normal curve centred at the observation, with width h and area one over n. Add the bumps up. The sum is a kernel density estimate: smooth, with total area one, and no bins to place. Where observations crowd together their bumps pile up; where they're sparse, the estimate is low. It's a histogram whose bins are centred on every point at once.
Everything depends on one choice, the bandwidth h. In gold, the World population histogram of heights, which a real analysis never sees. With h equal to one centimetre, every observation is its own little peak: the estimate tracks this sample's accidents. With h about four, the estimate follows the truth well. With h equal to ten, it's smeared: the peak is too low and the tails too fat. Too small a bandwidth is noisy, too large is biased. It's the bias–variance trade-off, which we'll meet everywhere from now on.
For IID draws from a twice-differentiable density at an interior point, the Gaussian-kernel trade-off can be written down. A wide bump flattens peaks and fills valleys: the bias is about one half h squared times the curvature of the density. A narrow bump averages over few points: the variance is about the density over n h, times a constant. Balancing the two, the best bandwidth shrinks like n to the minus one fifth, and the mean squared error like n to the minus four fifths: slower than the one over n of a parametric model. These rates require smoothness, positive density and nonzero curvature for the pointwise balance; they are not assumption-free. Bernard Silverman's rule of thumb, from his 1986 book, picks a bandwidth a little narrower than the best one for normal data, with a guard against outliers: four point one six centimetres for our sixty heights.
The bandwidth can also be chosen by cross-validation: leave each point out, and ask how well the estimate from the others predicts it. Which kernel you use matters little; the normal, the Epanechnikov parabola, all give similar pictures for the same effective width. In many dimensions kernel estimates need astronomically many points, the curse of dimensionality: Part 29 takes this up with nonparametric regression. And kernels and the bootstrap meet: resampling from the smooth estimate instead of the raw data is the smoothed bootstrap, one cure for the spiky bootstrap of the median in chapter seven.
Numbers: Silverman h = 4.16 cm for 60 heights
Recap, problems, and the road aheadAll tracks3 min
Part sixteen in thirteen lines. Efron asked for the standard error of a correlation from fifteen law schools, without a normal model. Permutation tests give exact p-values whenever the null makes the data exchangeable. The sign test uses only signs, and Fisher's sign flip has exact calibration under independent symmetric differences or a justified assignment mechanism. Wilcoxon's signed rank assumes independent symmetric continuous differences, and the Hodges–Lehmann estimate goes with it. Mann and Whitney's U counts pairs, and divided by their number it's the area under the ROC curve. Ranks extend to many groups, to blocks and to correlation. They cost four and a half percent at the normal, with a regular-location efficiency bound of 0.864, and can gain without limit. The jackknife estimates bias and standard error, and measures each point's influence, but fails for the median. The bootstrap mirrors the real world with the empirical distribution. Its intervals come in four kinds, and the Board found none of those four recipes reaches ninety-five percent for a mean of fifteen skewed incomes. For a maximum, its usual n-scaled bootstrap approximation fails. Cross-validation measures prediction honestly, and kernel estimates draw a density without bins, if the bandwidth is right.
Where it comes back. Part 17 resamples dependent data in blocks. Part 19 makes cross-validation the centre of model choice. Part 29 builds nonparametric regression from kernels and meets the curse of dimensionality. Part 30 proves the efficiency results and measures robustness with influence functions. Part 47 explains, with Edgeworth expansions, why the bootstrap-t and BCa are second-order accurate. Permutation methods return for multiple testing in Part 33, and exchangeability gives conformal prediction, intervals with guaranteed marginal coverage under exchangeability, in Parts 34 and 57.
Six problems, with full solutions in the README. A small permutation test; Wilcoxon's distribution for four pairs; the rank sum as a pair count; the jackknife and Bessel's correction; the chance a resample contains a given point; and why the percentile interval misses the tank total. Pause here if you want to try them.
The books and papers this part follows: Efron and Tibshirani's introduction to the bootstrap, Davison and Hinkley, Lehmann on ranks, Wasserman's all of nonparametric statistics and Silverman on density estimation, with the papers from Fisher and Wilcoxon to Efron, Hall and Parzen.
Sixteen parts of sixty-five, the sixth of Stage II. We can now test, estimate and draw intervals with very few assumptions. Now relax independence. The ordinary procedures illustrated here shuffled or resampled observations as if each were a separate draw. In 1926 George Udny Yule found that marriages in the Church of England correlated nought point nine five with mortality, and asked why time series produce such nonsense. Part 17: time series.
Where it goes next. Resampling in blocks handles dependent data in Part 17; cross-validation returns in Parts 19 and 28, kernels in Part 29, Pitman efficiency and influence functions in Part 30, exchangeability as conformal prediction in Parts 34 and 57, and the bootstrap's consistency is proved in Part 47.
Key results
The part's results in one place, for revision.
Try it
Lab 16 · The bootstrap, where it works and where it fails
Resample the 15 law schools to get the standard error of their correlation without a normal model, then resample 50 draws from Uniform(0, 1) and watch the bootstrap of the maximum pile up on one value, so that the percentile interval never covers.
python -m videos.stats.labs 16
needs numpy, scipy, matplotlib · download lab16.py ·
source on GitHublaw schools: r 0.776
SE of r: normal formula / jackknife / bootstrap 0.115 / 0.143 / 0.135
95% percentile interval for r [0.456, 0.962]
P*(resampled max = sample max), n = 50 0.635 (theory 0.636, limit 0.632)
percentile interval covers: the mean 93.8% (nominal 95%)
percentile interval covers: the maximum 0.0% (nominal 95%)
For a smooth statistic (a correlation, a mean) the resamples imitate the sampling distribution; for the maximum about 63% of them repeat the sample's own maximum, and the percentile interval never reaches the truth.
The code (84 lines; it asserts its own result)
"""Lab 16: bootstrap Efron's law schools, then break the bootstrap on the maximum of a uniform sample."""
import numpy as np
from videos.coursekit import labs
from explainer.stats import museum
from explainer.stats.kit import bootstrap as bs
TITLE = "The bootstrap, where it works and where it fails"
GOAL = ("Resample the 15 law schools to get the standard error of their correlation without a normal model, then "
"resample 50 draws from Uniform(0, 1) and watch the bootstrap of the maximum pile up on one value, so that "
"the percentile interval never covers.")
TASKS = [
"Replace the correlation by Spearman's (ranks.spearman). Is its bootstrap standard error larger or smaller?",
"Resample m = 10 of the n = 50 uniform draws and compare m(max - max*) with n(1 - max): does the spike shrink?",
"Change the statistic from the maximum to the median. Does the percentile interval's coverage recover?",
]
def corr(x, y):
return np.corrcoef(x, y)[0, 1]
def run(seed=0):
rng = np.random.default_rng(seed)
lab = labs.Lab()
# 1. the law schools: bootstrap and jackknife standard errors of r
lsat, gpa = np.array(museum.LAW_LSAT, float), np.array(museum.LAW_GPA, float)
r = corr(lsat, gpa)
reps = bs.bootstrap((lsat, gpa), corr, 4000, rng)
se_boot = reps.std(ddof=1)
jack = bs.jackknife((lsat, gpa), corr)
se_normal = (1 - r ** 2) / np.sqrt(len(lsat) - 3)
lo, hi = bs.percentile_ci(reps)
lab.row("law schools: r", f"{r:.3f}")
lab.row("SE of r: normal formula / jackknife / bootstrap", f"{se_normal:.3f} / {jack['se']:.3f} / {se_boot:.3f}")
lab.row("95% percentile interval for r", f"[{lo:.3f}, {hi:.3f}]")
assert abs(r - 0.776) < 0.001 and abs(jack["se"] - 0.143) < 0.001, "the film's numbers"
assert 0.122 < se_boot < 0.148 and se_boot > se_normal, "the bootstrap SE is near 0.135, above the normal formula"
# 2. the maximum of n uniforms: the spike, and the coverage of two intervals
n, B, R = 50, 400, 600
spike_theory = 1 - (1 - 1 / n) ** n
spikes, cover_max, cover_mean = [], 0, 0
for _ in range(R):
x = rng.uniform(0, 1, n)
xb = x[bs.resample_indices(n, B, rng)]
mx = xb.max(1)
spikes.append(np.mean(mx == x.max()))
a, b = bs.percentile_ci(mx)
cover_max += a <= 1.0 <= b
a, b = bs.percentile_ci(xb.mean(1))
cover_mean += a <= 0.5 <= b
spike = float(np.mean(spikes))
lab.row("P*(resampled max = sample max), n = 50", f"{spike:.3f} (theory {spike_theory:.3f}, limit {1 - np.exp(-1):.3f})")
lab.row("percentile interval covers: the mean", f"{cover_mean / R:.1%} (nominal 95%)")
lab.row("percentile interval covers: the maximum", f"{cover_max / R:.1%} (nominal 95%)")
assert abs(spike - spike_theory) < 0.01, "the spike is 1 - (1 - 1/n)^n"
assert cover_max == 0, "every resampled maximum is below theta"
assert 0.90 < cover_mean / R < 0.975, "the same interval works for the mean"
lab.note = ("For a smooth statistic (a correlation, a mean) the resamples imitate the sampling distribution; for "
"the maximum about 63% of them repeat the sample's own maximum, and the percentile interval never "
"reaches the truth.")
fig, ax = labs.figure(2, size=(11, 4.2))
ax[0].hist(reps, bins=50, color=labs.BLUE, alpha=0.7)
ax[0].axvline(r, color=labs.GOLD, label=f"r = {r:.3f}")
ax[0].axvline(lo, color=labs.MUTED, ls="--", label="2.5% and 97.5% points")
ax[0].axvline(hi, color=labs.MUTED, ls="--")
ax[0].set(title=f"Law schools: 4,000 resampled correlations (SE {se_boot:.3f})", xlabel="r*", ylabel="resamples")
ax[0].legend(loc="center left")
x = rng.uniform(0, 1, n)
real = n * (1 - rng.uniform(0, 1, (4000, n)).max(1))
boot = n * (x.max() - x[bs.resample_indices(n, 4000, rng)].max(1))
bins = np.linspace(0, 6, 49)
ax[1].hist(real, bins=bins, density=True, color=labs.GREEN, alpha=0.55, label="real world: n(θ − max)")
ax[1].hist(boot, bins=bins, density=True, color=labs.RED, alpha=0.55, label="bootstrap world: n(max − max*)")
ax[1].plot(bins, np.exp(-bins), color=labs.INK, lw=1.2, label="Exponential(1) limit")
ax[1].set(title="The maximum of 50 uniforms: a spike at zero", xlabel="scaled shortfall", ylabel="density",
ylim=(0, 3))
ax[1].legend()
lab.fig = fig
return lab
Now change it
- Replace the correlation by Spearman's (ranks.spearman). Is its bootstrap standard error larger or smaller?
- Resample m = 10 of the n = 50 uniform draws and compare m(max - max*) with n(1 - max): does the spike shrink?
- Change the statistic from the maximum to the median. Does the percentile interval's coverage recover?
Problems, with solutions
Try each problem before opening its solution.
1. A small permutation test. Two groups \(\{3, 5, 9\}\) and \(\{1, 2, 4\}\): the exact permutation \(p\)-value for the difference in means, one-sided.
Solution
The pooled values are 1, 2, 3, 4, 5, 9, and there are C(6, 3) = 20 ways to choose the first group. The observed group sums to 17. A group of three without the 9 sums to at most 3 + 4 + 5 = 12. A group with the 9 needs the other two to sum to at least 8: only {3, 5} and {4, 5}. So 2 of the 20 splits are as extreme, and p = 2/20 = 0.10.
2. Wilcoxon's distribution for n = 4. \(n = 4\): list the null distribution of Wilcoxon's \(W^+\), and find \(P(W^+ \ge 9)\).
Solution
Multiply out (1 + x)(1 + x²)(1 + x³)(1 + x⁴) = 1 + x + x² + 2x³ + 2x⁴ + 2x⁵ + 2x⁶ + x⁷ + x⁸ + x⁹ + x¹⁰. The coefficients sum to 16 = 2⁴, and P(W⁺ = w) is the coefficient over 16. Then P(W⁺ ≥ 9) = (1 + 1)/16 = 1/8. With four pairs, no one-sided test at level 0.05 is possible: the smallest p is 1/16.
3. The rank sum as a pair count. With no ties, show that \(U = R - m(m+1)/2\) counts the pairs \((i, j)\) with \(x_i > y_j\), where \(R\) is the rank sum of the \(x\)'s.
Solution
Assume no ties. Sort the x's: x₍₁₎ < … < x₍ₘ₎. The rank of x₍ₖ₎ in the pooled sample is k (the x's at or below it) plus the number of y's below it. Summing over k, R = m(m + 1)/2 + #{(i, j) : xᵢ > yⱼ}. So U = R − m(m + 1)/2 is the pair count. With ties, average ranks give half credit to tied cross-group pairs.
4. The jackknife and Bessel's correction. Show that the jackknife bias correction of \(\hat\sigma^2 = \frac1n\sum(x_i - \bar x)^2\) gives exactly \(s^2\).
Solution
Let SS = Σ(xⱼ − x̄)² and dᵢ = xᵢ − x̄. Leaving out xᵢ, Σⱼ≠ᵢ(xⱼ − x̄₍ᵢ₎)² = SS − n dᵢ²/(n − 1), so σ̂²₍ᵢ₎ = [SS − n dᵢ²/(n − 1)]/(n − 1).
- The average: since Σdᵢ² = SS, the mean of the σ̂²₍ᵢ₎ is SS(n − 2)/(n − 1)².
- The bias estimate: (n − 1)[SS(n − 2)/(n − 1)² − SS/n] = −SS/(n(n − 1)).
- The corrected estimate: SS/n + SS/(n(n − 1)) = SS/(n − 1) = s².
5. The chance a resample contains a point. For \(n\) distinct values, find \(P^*(\text{a resample contains } x_1)\), and its limit.
Solution
Each of the n draws misses x₁ with probability 1 − 1/n, independently. So P*(x₁ in the resample) = 1 − (1 − 1/n)ⁿ, which tends to 1 − 1/e ≈ 0.632. On average a resample contains about 63% of the distinct points.
6. The percentile interval for a maximum. Show that the percentile interval for \(\max_i x_i\) from Uniform\((0, \theta)\) never contains \(\theta\).
Solution
Every resampled value is one of the xᵢ, so every resampled maximum is at most maxᵢ xᵢ. Hence both percentiles are at most maxᵢ xᵢ. But maxᵢ xᵢ < θ with probability 1, since the uniform has no atom at θ. So the interval lies below θ and never contains it: coverage 0, as on the Board.
Notes and sources
Where it comes back
| Idea | Returns in |
|---|---|
| block bootstraps for dependent data | 17 |
| cross-validation and model choice | 19, 28 |
| kernels, nonparametric regression, the curse of dimensionality | 29 |
| influence functions; Pitman efficiency proved | 30 |
| permutation methods for many tests | 33 |
| conformal prediction from exchangeability | 34, 57 |
| bootstrap consistency, Edgeworth expansions, the uniform maximum | 47 |
| the Coverage Board | every part; 65 |
Glossary
- Exchangeable: a joint distribution unchanged by permuting the observations.
- Permutation test: a test whose null distribution is the statistic over all relabellings the null makes equally likely.
- Sign test: the test of a zero median from the number of positive differences, Binomial(n, ½) under H₀.
- Signed-rank statistic (W⁺): the sum of the ranks of |dᵢ| over the positive dᵢ.
- Walsh averages: (dᵢ + dⱼ)/2 for i ≤ j; their median is the Hodges–Lehmann estimate.
- Rank-sum statistic, Mann–Whitney U: the sum of one group's pooled ranks; U subtracts its minimum and counts pairs.
- Midranks: the average rank given to tied values.
- AUC: the area under the ROC curve; equals U/(mn), an estimate of P(X > Y) + ½P(X = Y).
- Kruskal–Wallis H; Friedman Q: rank analogues of the one-way ANOVA and the randomized-block ANOVA.
- Spearman's r_S; Kendall's τ: Pearson's correlation of the ranks; (concordant − discordant)/C(n, 2).
- Asymptotic relative efficiency (ARE): the limiting ratio of sample sizes two tests need for equal power.
- Contaminated normal: a mixture of a normal with a small share of a much wider normal.
- Jackknife: leave-one-out recomputation, giving estimates of bias and standard error.
- Empirical distribution F̂ₙ: mass 1/n on each observation.
- Bootstrap: estimating a sampling distribution by resampling from F̂ₙ with replacement.
- Percentile, basic, bootstrap-t, BCa intervals: four ways to turn replicates into an interval.
- Bias correction z₀; acceleration a: BCa's adjustments, from the share of replicates below the estimate and the jackknife's skewness.
- Parametric bootstrap: resampling from a fitted model rather than from F̂ₙ.
- m-out-of-n bootstrap: resampling fewer points than the sample has, to repair some failures with statistic-specific scaling and m → ∞, m/n → 0.
- Cross-validation (K-fold, leave-one-out): estimating prediction error by predicting held-out data.
- Optimism: how much the training error understates the test error; 2σ²p/n for a fixed full-rank homoskedastic linear model and fresh responses at the same design.
- PRESS: the leave-one-out prediction sum of squares, Σ(eᵢ/(1 − hᵢᵢ))².
- Kernel density estimate; bandwidth: an average of bumps K((x − xᵢ)/h)/h; h is their width.
Sources
- Permutation and rank tests.
- C. Darwin, The Effects of Cross and Self Fertilisation in the Vegetable Kingdom (1876); R. A. Fisher, The Design of Experiments (1935), §17.
- F. Wilcoxon, Biometrics Bull. 1 (1945); H. Mann & D. Whitney, Ann. Math. Stat. 18 (1947).
- W. Kruskal & W. A. Wallis, JASA 47 (1952); M. Friedman, JASA 32 (1937).
- C. Spearman, Am. J. Psych. 15 (1904); M. Kendall, Biometrika 30 (1938).
- D. Bamber, J. Math. Psych. 12 (1975).
- Efficiency.
- E. Pitman, lecture notes on nonparametric inference (1948); J. Hodges & E. Lehmann, Ann. Math. Stat. 27 (1956), 34 (1963); J. Tukey, in Contributions to Probability and Statistics (1960).
- Resampling.
- M. Quenouille, JRSS B 11 (1949), Biometrika 43 (1956); J. Tukey, Ann. Math. Stat. 29 (abstract, 1958).
- B. Efron, Ann. Stat. 7 (1979); JASA 82 (1987); The Jackknife, the Bootstrap and Other Resampling Plans (1982).
- P. Bickel & D. Freedman, Ann. Stat. 9 (1981); P. Hall, Ann. Stat. 16 (1988); P. Bickel, F. Götze & W. van Zwet, Stat. Sinica 7 (1997).
- Prediction and smoothing.
- M. Stone, JRSS B 36 (1974); S. Geisser, JASA 70 (1975); D. Allen, Technometrics 16 (1974); C. Mallows, Technometrics 15 (1973).
- M. Rosenblatt, Ann. Math. Stat. 27 (1956); E. Parzen, Ann. Math. Stat. 33 (1962); B. Silverman, Density Estimation for Statistics and Data Analysis (1986).
- Books.
- B. Efron & R. Tibshirani, An Introduction to the Bootstrap (1993); A. Davison & D. Hinkley, Bootstrap Methods and their Application (1997).
- E. Lehmann, Nonparametrics: Statistical Methods Based on Ranks (1975; rev. 2006); L. Wasserman, All of Nonparametric Statistics (2006).
About this partfrom its README
Part 16 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. Every interval since Part 8 leaned on a model for the data. This part asks how far we can get without a parametric shape model. It still requires assumptions: IID sampling and regularity for the ordinary bootstrap, exchangeability for label permutations, and symmetry/continuity for the untied signed-rank law. Exact calibration is distinguished from asymptotic approximation throughout.
It opens with Efron's paper of 1979 and his running example: 15 American law schools, LSAT against GPA, r = 0.776. The normal-theory standard error is 0.115; the bootstrap's, without a normal shape model, is 0.135.
From there the part covers:
- Permutation tests. Exchangeability under H₀ makes every relabelling equally likely. All 2,704,156 splits of 24 incomes from the World give p = 0.232 (Welch: 0.237); shuffling GPAs against LSATs gives p ≈ 0.0017 for the law schools' correlation.
- Signs and signed ranks. Darwin's maize (Fisher 1935): the sign test (p = 0.0074), Fisher's 2¹⁵ sign flips (1,726 as extreme, p = 0.053), Wilcoxon's W⁺ = 96 with its exact null from the generating function ∏(1 + xᵏ)/2 (p = 0.041), and the Hodges–Lehmann estimate and interval from the Walsh averages.
- Mann–Whitney. The Challenger temperatures: midranks, U as a count of 112 pairs (87.5), its exact null, and U/(mn) = 0.781, the area under the ROC curve. What the test does and does not test.
- More rank methods. Kruskal–Wallis on three regions' incomes, Friedman's test for blocks, Spearman's and Kendall's correlations, and how one bad value moves Pearson's r much more than the rank correlations.
- Efficiency. Pitman's ARE; power of t and Wilcoxon–Mann–Whitney under normal, t₃ and contaminated errors; the efficiency table and Hodges–Lehmann's bound 0.864; both tests keep their size (the Board).
- The jackknife. Leave-one-out correlations, Quenouille's bias and Tukey's SE (0.143), Bessel's correction rediscovered, influence, and the jackknife's failure for the median.
- The bootstrap principle. The
BootstrapResampler; 2,000 resampled correlations; Efron's two worlds; a check in the World (median income, n = 25: real SD 6.06 vs bootstrap 4.72); how many resamples; what it assumes. - Bootstrap intervals. Percentile, basic (which passes 1 here), bootstrap-t on skewed incomes, BCa stated with z₀ = −0.137 and a = −0.076; five intervals compared; four Board rows.
- When it fails. The uniform maximum: P*(θ̂* = θ̂) = 1 − (1 − 1/n)ⁿ → 1 − 1/e. The percentile interval covers 0%. Fixes: a 95% one-sided pivot interval [M, M/0.05^(1/n)], a parametric pivot bootstrap (not a raw percentile interval), and properly rate-scaled m-out-of-n with m → ∞ and m/n → 0.
- Cross-validation. Polynomials in age for log income; training error vs 10-fold CV (best: degree 3); the optimism 2σ²p/n; leave-one-out and PRESS; cautions.
- Density estimates. The histogram's arbitrary bins; the
KernelSum; bandwidths 1, 4.16 (Silverman) and 10 against the full-population histogram; the bias–variance trade-off and n^(−1/5).
Every number on screen is computed in compute.py or inline in a scene:
- the law schools (Efron & Tibshirani 1993, Table 3.1), Darwin's differences (Fisher 1935) and the Challenger temperatures come from the Museum or the scene;
- incomes, ages and heights are the World's (seed 1662);
- the efficiency and failure simulations are seeded.
Built in this part:
statkit.ranks(explainer/stats/kit/ranks.py), checked against SciPy intests/test_stats_kit_ranks.py:- the exact signed-rank null by generating function, and the signed-rank test;
- the untied Mann–Whitney null by recursion; this part uses a local conditional-midrank recursion for tied temperatures;
- Kruskal–Wallis, Spearman and Kendall.
statkit.bootstrap(explainer/stats/kit/bootstrap.py), checked intests/test_stats_kit_bootstrap.py:- resampling, the bootstrap and the jackknife (bias, SE, leave-one-out values);
- percentile, basic, normal, BCa and bootstrap-t intervals;
- Silverman's bandwidth, the Gaussian kernel density estimate, and K-fold cross-validation of polynomial fits.
- The bootstrap resampler (
BootstrapResamplerinexplainer/stats/viz.py): the sample as tokens, copied with replacement into a resample row; each replicate dropped as a dot. - The kernel sum (
KernelSuminexplainer/stats/viz.py): one bump per observation and their sum.
The Coverage Board gains eight rows, R = 10,000 (bootstrap intervals with B = 999).
| Method | Setting | Achieved | Verdict |
|---|---|---|---|
| bootstrap percentile | the World's incomes, n = 15 | 85.51% | broken |
| bootstrap BCa | the World's incomes, n = 15 | 86.66% | broken |
| bootstrap-t | the World's incomes, n = 15 | 91.64% | broken |
| Student's t | the World's incomes, n = 15 | 88.40% | broken |
| percentile, the maximum | Uniform(0, θ), n = 50 | 0.00% | broken |
| basic, the maximum | Uniform(0, θ), n = 50 | 87.80% | broken |
| t-test (size) | contaminated normal, 20 + 20 | 4.39% | kept |
| Wilcoxon–Mann–Whitney (size) | contaminated normal, 20 + 20 | 5.18% | kept |
Chapter notes
| # | Chapter | Numbers |
|---|---|---|
| 0 | Fifteen law schools, 1979 | r = 0.776; SE 0.115 (normal formula), 0.135 (bootstrap) |
| 1 | Permutation tests | 12 + 12 incomes, difference −20.4; 2,704,156 splits, p = 0.232; Welch 0.237; law schools p ≈ 0.0017 |
| 2 | Signs and signed ranks | 13 of 15 positive, sign p = 0.0074; Fisher 1,726/32,768 = 0.053; W⁺ = 96, p = 0.041; t p = 0.050; Hodges–Lehmann 25, 95.2% CI [4.0, 41.5] |
| 3 | Mann–Whitney | rank sum 52.5, U = 87.5 of 112, conditional exact p = 0.03352 (0.03757 tie-corrected normal approximation); AUC 0.781 |
| 4 | More rank methods | H = 1.53, p = 0.47 (F = 0.36, p = 0.70); Friedman Q = 10.2; Spearman 0.796, Kendall 0.638 (86 vs 19 pairs); one bad GPA: 0.148, 0.436, 0.390 |
| 5 | Efficiency | power t / WMW: 0.69 / 0.66 (normal), 0.77 / 0.89 (t₃), 0.35 / 0.52 (contaminated); ARE 0.955, 1.097, 1.5, 1.90, 2.41; bound 0.864 |
| 6 | The jackknife | bias −0.0065, SE 0.143; without school 1, r = 0.893; LSAT median: 3 distinct values, SE 14.7 vs 18.4 |
| 7 | The bootstrap principle | SE 0.135; median income: truth 38.9, sample 37.65, SD 6.06 real vs 4.72 bootstrap; 77,558,760 distinct resamples |
| 8 | Bootstrap intervals | percentile [0.447, 0.962], basic [0.591, 1.106], normal [0.513, 1.040], BCa [0.287, 0.943], Fisher z [0.439, 0.922]; incomes: t [28.0, 56.9], percentile [30.7, 55.5], bootstrap-t [30.2, 61.7], truth 49.5 |
| 9 | When it fails | P*(spike) 0.625 (theory 0.636, limit 0.632); exact one-sided 95% CI [0.966, 1.026] |
| 10 | Cross-validation | best degree 3, CV 0.3425; optimism: 0.3395 vs CV 0.3425 (degree 3), 0.3493 vs 0.3536 (degree 8) |
| 11 | Density estimates | Silverman h = 4.16 cm for 60 heights |
| 12 | Outro | — |
Companion material in this repository
The syllabus's plan for this partfrom SYLLABUS.md, the plan of record
- Hook: Efron (1979). The law-school sample, r = 0.776: what is its SE?
- Permutation tests. Exchangeability under H₀; exact p-values; the permutation machine (Part 10) returns.
- The sign test and Wilcoxon's signed rank (1945). The exact null by generating function.
- Mann–Whitney (1947). U counts pairs; U/(mn) is the AUC.
- More rank methods. Kruskal–Wallis, Spearman, Kendall.
- Efficiency, first look. Wilcoxon loses only 4.5% at the normal and can win under heavy tails (computed; Part 30 proves it).
- The jackknife (Quenouille 1949; Tukey 1958).
- The bootstrap principle. The real world mirrored by the bootstrap world (
BootstrapResampler). - Bootstrap intervals. Percentile, basic, t; BCa, stated (Board).
- When it fails. The uniform maximum: P(θ̂* = θ̂) → 1 − 1/e (the tanks again).
- Cross-validation. Estimating prediction error by holding out (Part 19).
- Density estimates, first look. Kernel smoothing as a sum of bumps (
KernelSum; Part 29). - Outro.
Built: statkit.bootstrap and statkit.ranks. Data: the law-school sample.
Build the film
python -m videos.stats.stats16.compute # the part's numbers, into .cache/stats16
python tools/build.py stats16 # render and assemble the film
EXPLAINER_TTS=silent python tools/qa_scene.py stats16 Hook # one chapter, silent, with a contact sheet
Scenes: videos/stats/stats16. Setup: see the course page. Source of these notes: the README and the scenes' narration.
Build it
python -m videos.stats.stats16.compute # once (a few minutes; cached in .cache/stats16)
python tools/build.py stats16 -q l # fast 480p preview
python tools/build.py stats16 # 1080p30 -> renders/stats16.mp4
python tools/qa_scene.py stats16 Principle
python tools/lecture_length.py stats16 --floor 50