24.5 Statistics
Every model in this book is eventually judged by a number computed on held-out data: a test accuracy, a validation loss, or a benchmark score. We tend to treat that number as an intrinsic property of the model, yet it also reflects the particular examples that happened to land in the test set. Suppose a classifier answers 912 of 1,000 test questions correctly, giving an accuracy of 91.2%. On a different set of 1,000 questions from the same source, it would score slightly higher or slightly lower, so 91.2% is really one realization of a random variable. Now suppose a second model answers 921 of those same questions correctly. Is it actually better, or did this particular batch of questions happen to favor it?
Statistics answers questions like this by asking how an estimate would fluctuate across all the alternative samples we never drew. Those fluctuations follow a distribution, the sampling distribution of the estimate, and every tool in this section is built to describe it or reason with it. Its center and spread tell us whether an estimate is systematically off target and how widely it scatters. A hypothesis test checks whether an observed difference fits comfortably inside the scatter that chance alone would produce. A confidence interval collects all parameter values that the data cannot rule out. And when no closed-form formula describes the sampling distribution, the bootstrap simulates it directly from the data in hand.
In deep learning, these tools matter because almost every engineering decision rests on comparing noisy numbers: which model to deploy, which hyperparameter wins, or whether a new idea helped. Acting on a gap smaller than its own noise is no better than flipping a coin. Whereas the earlier sections of this chapter described how data behave when the underlying distribution is known, this section works in the opposite direction, turning observed data into estimates with honest error bars. The data need not even come from the outside world. When we approximate an expectation by averaging samples generated on a computer (a Monte Carlo estimate), the result is just another sample mean, so the same theory gives its error bar (Section 24.5.1.7). Likewise, test accuracy behaves like a coin tossed once per question, so the coin from earlier sections (9 heads in 13 flips) will reappear along the way as a sanity check.
If you remember only three ideas from this section, make them these: mean squared error splits cleanly into squared bias plus variance; a -value is uniformly distributed when the null hypothesis is true; and a confidence interval is simply the set of parameter values that a hypothesis test fails to reject. On a first reading, you can safely skim the discussions of consistency and the delta method. Keep one caveat in mind throughout: every guarantee below assumes that the estimator or test was chosen before looking at the data. At the end of the section, we will see how easily those guarantees break down when they are not.
from scipy.stats import norm
rng = np.random.default_rng()
24.5.1 Estimators and Their Sampling Distribution#
Before we can decide how much to trust that 91.2% accuracy, we need a precise name for the rule that produced it and a simple probability model for how the test questions arrived.
24.5.1.1 Estimators and the Sample Proportion#
An estimator is any rule that turns a sample into a number intended to approximate an unknown parameter . The sample mean, the sample median, and the fraction of correct answers on a test set are all estimators. Because the data are random, is random too, and its distribution across repeated samples of size is its sampling distribution.
To model our classifier's test accuracy, let if the model answers question correctly and otherwise. Assuming the test questions are drawn independently from a large pool on which the classifier's true accuracy is , the indicators are i.i.d. Bernoulli random variables with mean . Our estimate is the sample proportion of correct answers among the questions. By linearity of expectation, , and as in Section 1.6, its variance is . In other words, the sample proportion is centered right on the true accuracy, and its typical error shrinks at the rate . Plugging in and gives a standard deviation of , or about 0.9 percentage points. By the central limit theorem, the sampling distribution is closely approximated by a Gaussian, so roughly 95% of test sets yield an accuracy within percentage points of .
Rather than relying on formulas alone, we can observe this sampling distribution directly. Let us simulate 10,000 independent test sets of 1,000 questions for a classifier whose true accuracy is , and check the mean and spread of the resulting accuracies.
theta, n = 0.912, 1000
acc = rng.binomial(n, theta, 10000) / n # accuracy on 10,000 test sets
print(f'mean {acc.mean():.4f}, std {acc.std():.4f}, '
f'formula {np.sqrt(theta * (1 - theta) / n):.4f}')mean 0.9119, std 0.0089, formula 0.0090
Just as the formula predicted, the simulated accuracies cluster around with a standard deviation of . That cloud of 10,000 numbers, representing accuracies on hypothetical test sets we never drew, is the object that every tool in this section reasons about.
Now return to our second model, which answered 921 questions correctly. If its score had been measured on a separate, independent test set of 1,000 questions, the observed gap of between the two accuracies would have a standard deviation of , where comes from evaluating the same formula at . A gap of is only about 0.7 of its own standard error, nowhere near enough to separate the two models. Here, however, both models were evaluated on the same 1,000 questions. In Section 24.5.2.6, we will see how much sharper the comparison becomes once we take advantage of that shared test set.
24.5.1.2 Bias and Variance#
An estimator can miss the truth in two distinct ways: it can aim off center on average, or it can scatter widely around its own average. The bias of measures the first kind of error, the systematic offset between the estimator's average value and the true parameter,
where the expectation is taken over the random draw of the sample. When the bias is zero for every possible value of , we call the estimator unbiased. The variance measures the second kind of error, how widely fluctuates around its own center, and its square root is the standard error,
Put simply, bias tells us where the estimates land on average, while standard error tells us how far a typical draw lands from that average. In our accuracy example, the sample proportion has bias and standard error . Notice that variance is measured around the estimator's own mean, not around : a stubborn rule that ignores the data completely and always outputs has zero variance, so all of its error comes from bias.
24.5.1.3 The Sample Variance#
The sample proportion is unbiased, which might make unbiasedness seem automatic. Yet a biased estimator shows up immediately as soon as we try to compute a standard error from data. The standard error of a sample mean depends on the population variance , which is almost never known and must be estimated from the same sample. The most natural choice is the plug-in variance, the average squared deviation from the sample mean ,
Surprisingly, is systematically too small. Why? Because is the unique point that minimizes the sum of squared deviations for this particular sample. Measuring deviations from the true mean , a different point, always yields a larger sum, so replacing by shrinks the numerator.
The smallest nontrivial sample, , makes the size of this shrinkage obvious. Here the sample mean is simply the midpoint of and , so both deviations equal , giving
Because and are independent with mean and variance , their difference has mean and variance . The right-hand side therefore has expectation . If we divide by , we get on average, only half the true variance. Dividing by instead recovers on average. Remarkably, the exact same correction removes the bias for every sample size .
Proposition (unbiased sample variance). Let be i.i.d. with mean and finite variance , and let . Then
Proof. To compare the deviations around with those around , write and expand the square. Using to simplify the cross term gives
The cross term is twice the final term with the opposite sign, so centering at instead of subtracts from the sum of squares. Now take expectations of both sides. Each term equals , so the first sum has expectation . Meanwhile, the sample mean has variance , so . The sum of squared deviations therefore has expectation , and dividing by yields .
A helpful way to remember this factor is through degrees of freedom. The deviations are constrained to sum to zero, so only of them can vary freely: estimating from the data uses up one degree of freedom. The plug-in variance has bias , which matters at small and vanishes as the sample grows.
One caveat is worth noting: unbiasedness does not survive nonlinear transformations. By Jensen's inequality applied to the concave square-root function, , with strict inequality whenever is not constant. For Gaussian data at , the sample standard deviation is , whose expectation is . Thus, taking the square root of an unbiased variance estimate still underestimates the standard deviation by 20% on average.
In numerical libraries, you choose between these two denominators with a
"delta degrees of freedom" flag: np.var(x, ddof=0) divides by , while
np.var(x, ddof=1) divides by .
24.5.1.4 The Bias–Variance Decomposition#
To see bias and variance interact, let us construct an estimator that deliberately trades one for the other. Suppose we observe noisy measurements with and . The ordinary sample mean is unbiased, with variance (standard error ). Now consider the shrunk mean for a factor , which pulls the sample mean toward . Pulling toward zero introduces a bias of , but it also compresses the variance to . At , the bias is , while the standard error drops sharply from to . Figure 24.5.1 shows both sampling distributions side by side.
Sampling distributions of two estimators of from 30 draws of . Left: the sample mean , with bias 0 and standard error 0.73. Right: the shrunk mean , with bias and standard error 0.47. Bias is the offset of the center from ; standard error is the width.
Which estimator is actually better? The shrunk mean is systematically off target, yet because it scatters much less, any single draw from it often lands closer to than does. To settle the comparison, we need a single score that accounts for both errors at once. The mean squared error (MSE) is the average squared distance from the estimator to the true parameter,
Conveniently, the MSE decomposes cleanly into the two quantities we just defined.
Proposition (bias–variance decomposition). If has finite variance, then
Proof. Let be the center of the estimator, and add and subtract inside the square:
Now take expectations term by term. The first term gives , and the third is the constant . The cross term vanishes because is a constant and by definition of .
There is a nice geometric way to picture this identity: it is Pythagoras' theorem in disguise. If we treat random variables as vectors equipped with the inner product , then the zero-mean fluctuation is orthogonal to every constant , since . Writing the total error as the sum of this fluctuation and the constant bias therefore breaks it into two perpendicular legs of lengths and , whose squared lengths sum to the squared hypotenuse . From this viewpoint, is the orthogonal projection of onto the subspace of constants, the same projection we met in Section 21.1 with expectation playing the role of the dot product. Figure 24.5.2 illustrates this right triangle.
The bias–variance decomposition as Pythagoras' theorem for estimators of from 30 draws of . Each estimator sits at horizontal coordinate and vertical coordinate , so its distance from the origin is . Shrinking to adds a horizontal leg of 0.35 but cuts the vertical leg from 0.73 to 0.47, reducing the hypotenuse to 0.59 and placing it inside the dashed circle of estimators as accurate as . The sample median is unbiased but lies outside the circle.
With the decomposition in hand, we can rank estimators quantitatively. For our 30-observation problem, the formula predicts an MSE of for the sample mean (all variance) and for the shrunk mean . What about the sample median? By symmetry of the Gaussian it is unbiased, though we do not yet have a formula for its variance. Let us simulate 10,000 data sets of size 30 and compare all three estimators empirically.
theta, sigma, n = 1.0, 4.0, 30
data = rng.normal(theta, sigma, (10000, n)) # 10,000 data sets of size 30
estimates = {'mean': data.mean(axis=1),
'0.65 * mean': 0.65 * data.mean(axis=1),
'median': np.median(data, axis=1)}
For each estimator in estimates, we now compute its empirical squared bias,
variance, and total MSE across the 10,000 simulated datasets and compare the
sum against our analytical predictions:
predicted = {'mean': sigma**2 / n, # bias^2 + variance, by formula
'0.65 * mean': (0.35 * theta)**2 + 0.65**2 * sigma**2 / n,
'median': None} # no formula yet
print(f'{"estimator":>12} {"bias^2":>7} {"var":>6} {"MSE":>6} {"predicted":>9}')
for name, est in estimates.items():
bias2 = (est.mean() - theta) ** 2
var = est.var() # a plain average: divides by the count
mse = ((est - theta) ** 2).mean()
pred = '-' if predicted[name] is None else f'{predicted[name]:.3f}'
print(f'{name:>12} {bias2:7.3f} {var:6.3f} {mse:6.3f} {pred:>9}') estimator bias^2 var MSE predicted
mean 0.000 0.532 0.532 0.533
0.65 * mean 0.125 0.225 0.350 0.348
median 0.000 0.805 0.805 -
The simulation confirms the formulas: the sample mean has an MSE near , while the shrunk mean lands at . The sample median trails at about ; even though it is unbiased, its variance is roughly half again as large as that of . Notice the takeaway: a biased estimator can clearly outperform an unbiased one, and being unbiased is no guarantee of accuracy.
24.5.1.5 The Shrunk Mean and the Trade-off#
This comparison immediately raises a practical question: how much bias should we accept in exchange for lower variance? For the shrunk mean , we can solve this trade-off in closed form. Substituting its bias and variance into (24.5.5) gives
As we shrink toward zero, the squared bias grows while the variance falls. Differentiating with respect to and setting yields the optimal shrinkage factor and its minimum error,
Notice that the optimal shrinkage always beats the unshrunk sample mean, and it helps most when the noise is large relative to the signal . For our running numbers (, , ), the formula gives , the factor we chose earlier, and cuts the MSE from down to . Figure 24.5.3 plots both error components and their sum against . Here the classic U-shaped curve is exact, since it is simply the sum of a decreasing parabola and an increasing one.
Squared bias and variance of the shrunk mean as functions of , for , , and . Their sum, the MSE, reaches its minimum at , dropping to 0.35 compared with 0.53 for the unshrunk sample mean at .
Of course, there is a catch: depends on the unknown parameter , so we cannot compute it directly from data. Worse, picking a fixed shrinkage factor without knowing can backfire badly. If the true mean were , using the same would incur a bias of and an MSE of , more than twenty times worse than the of . Shrinking toward helps only when the truth actually lies near . Exercise 1 explores what happens when we plug an estimate of into , and exercise 9 reveals a famous surprise: in three or more dimensions, a similar data-driven shrinkage beats the sample mean for every value of .
This same bias–variance trade-off governs supervised prediction. At any fixed input , the prediction of a model trained on a random data set is an estimator of the true regression function . Its expected squared error on a fresh label equals the MSE of that estimator plus the irreducible variance of the label noise (Section 2.6). Across many model families, adding flexibility reduces bias while increasing variance, and regularization acts much like the shrinkage factor (Geman et al., 1992). Keep in mind, though, that test error in modern overparameterized models does not always trace a simple U-shape: beyond the interpolation threshold where a model fits its training data exactly, test error can descend a second time (Section 24.10.3.2).
24.5.1.6 Consistency and Efficiency#
Bias and variance evaluate an estimator at a fixed sample size . A separate question is what happens as we gather more and more data: does the estimate eventually lock onto the truth? We say that an estimator is consistent if it converges in probability to , meaning
written . Intuitively, for any tolerance , the probability of missing by more than shrinks to zero as the sample grows.
The bias–variance decomposition gives us a quick way to check consistency. Applying Markov's inequality (Section 24.1) to the nonnegative random variable with threshold bounds the probability of a large error directly by the MSE:
Consequently, if both the bias and the variance vanish as , the estimator is guaranteed to be consistent. Neither condition is enough on its own. Keeping only the first observation, , is unbiased for every , yet its variance stays stuck at so it never converges. Conversely, has variance , yet it converges to the wrong value. The plug-in variance illustrates the happy middle ground: even though it is biased at every finite , its bias and variance (assuming a finite fourth moment) both vanish as grows, so it is consistent.
Applying this bound to the sample mean yields the foundational result that makes averaging work.
Proposition (weak law of large numbers). If are i.i.d. with mean and finite variance , then the sample mean satisfies
Proof. By linearity of expectation, , so the bias is zero. Because the variables are independent, the variance of their sum is the sum of their variances, giving . Substituting into the Markov bound above produces the inequality, whose right-hand side tends to zero as .
In fact, the law holds under the weaker assumption of a finite mean , though the proof is longer (Wasserman, 2013). This simple theorem underpins much of machine learning: it explains why a Monte Carlo estimate of an integral converges, why accuracy on a large test set reflects true accuracy, and why average training loss tracks expected loss. That said, the bound itself is quite loose. For our 91.2%-accurate classifier on 1,000 questions, it only guarantees that the test accuracy misses by more than 3 percentage points with probability at most , whereas the Gaussian approximation puts that probability near . Its real strength is generality: it assumes nothing beyond finite variance. In Section 24.9, we will derive far tighter bounds when stronger tail assumptions hold.
Consistency is only a baseline; it does not distinguish between two consistent estimators. Among unbiased estimators, the one with smaller variance is more efficient, meaning it achieves the same precision with fewer samples. For Gaussian data, both the sample mean and the sample median are unbiased for , but for large the median's variance is roughly (exercise 6). The median therefore requires about times as much data to match the mean's standard error, giving it an efficiency of . Our simulation already hinted at this ratio: against . By contrast, the sample proportion achieves the smallest possible variance of any unbiased estimator of a Bernoulli parameter, a fundamental lower limit known as the Cramér–Rao bound (Section 24.6.3.4).
24.5.1.7 Monte Carlo Estimation#
Up to now, our samples came from external data: test questions, noisy measurements, or training runs. Yet the law of large numbers does not care where the samples come from, which turns the sample mean into a powerful computational tool. Most expectations we encounter in deep learning (an expected loss, a normalizing constant, or the gradient of either) are integrals with no closed form, often spanning thousands of dimensions where numerical grids are hopelessly expensive. Even when we cannot build a grid, we can usually draw samples. The idea goes back to the earliest electronic computers (Metropolis and Ulam, 1949): to approximate for a random variable with density , draw independent samples from and average the function values,
You can think of a Monte Carlo estimate as a Riemann sum whose evaluation points are chosen at random with equal weight , automatically placing more points where the density is high. By the law of large numbers (24.5.6), this average is unbiased and converges to as . Its convergence rate is governed by its variance: if are i.i.d. with density and is finite, then
There is nothing mathematically new here: this is just the variance of a sample mean from the law of large numbers, with playing the role of (Section 24.2). What is remarkable is the consequence. The root-mean-square error shrinks as . On the face of it, that is slow: gaining one extra decimal digit of accuracy requires 100 times as many samples. Yet the dimension of never appears in the exponent, and that dimension-independence is the entire reason sampling works in high dimensions. The one essential requirement is finite variance; as we saw in Section 24.1, heavy tails can derail an average (see exercise 5).
Compare this with a deterministic grid. Reaching grid spacing in dimensions requires evaluation points. The left-endpoint rule of Section 22.6 has error proportional to , and a second-order rule such as the midpoint rule (evaluating each cell at its center) improves this to . Monte Carlo, meanwhile, keeps its rate in every dimension. In one dimension, the midpoint grid wins easily; at , the exponents tie; by , the grid slows to while Monte Carlo still converges at . Although the numerator can still grow with , the exponent never degrades (exercise 7).
Let us see this rate in action on a concrete integral: for uniform on . Its exact value is . Below, we track the running average across powers of ten, comparing the actual error against the predicted scale , where is estimated from the samples.
exact = math.sqrt(math.pi) / 2 * math.erf(1)
g = np.exp(-rng.uniform(size=10**5)**2) # g(U), U uniform on [0, 1]
running = np.cumsum(g) / np.arange(1, 10**5 + 1) # average of the first n
sigma = g.std()
for n in [10, 100, 1000, 10000, 100000]:
print(f'n={n:<6} estimate={running[n - 1]:.5f} '
f'error={abs(running[n - 1] - exact):.1e} sigma/sqrt(n)={sigma / n**0.5:.1e}')
print(f'exact (sqrt(pi)/2) erf(1) = {exact:.6f}')n=10 estimate=0.87045 error=1.2e-01 sigma/sqrt(n)=6.4e-02
n=100 estimate=0.77742 error=3.1e-02 sigma/sqrt(n)=2.0e-02
n=1000 estimate=0.74604 error=7.8e-04 sigma/sqrt(n)=6.4e-03
n=10000 estimate=0.74536 error=1.5e-03 sigma/sqrt(n)=2.0e-03
n=100000 estimate=0.74705 error=2.3e-04 sigma/sqrt(n)=6.4e-04
exact (sqrt(pi)/2) erf(1) = 0.746824
The observed errors track the predicted scale closely, though each row is still just one random realization: a single error rarely exceeds by more than a factor of two or three, and occasionally drops well below it. To see how the error behaves continuously across sample sizes, let us plot one running average at 200 log-spaced values of alongside the root-mean-square error over 200 independent runs, which is the exact quantity predicted by (24.5.8).
n = np.unique(np.logspace(1, 5, 200).astype(int))
sq = np.zeros(len(n))
for _ in range(200): # 200 independent runs
g_run = np.exp(-rng.uniform(size=10**5)**2)
sq += (np.cumsum(g_run)[n - 1] / n - exact)**2
rms = np.sqrt(sq / 200) # root-mean-square error
ratio = rms * np.sqrt(n) / sigma
print(f'RMS error / (sigma/sqrt(n)) over all n: {ratio.min():.2f} to {ratio.max():.2f}')
d2l.plot(n, [np.abs(running[n - 1] - exact), rms, sigma / np.sqrt(n)],
'samples n', 'error', xscale='log', yscale='log',
legend=['one run', 'RMS over 200 runs', 'sigma / sqrt(n)'])RMS error / (sigma/sqrt(n)) over all n: 0.87 to 1.08
Notice the difference between the two curves. A single running average wanders above and below the theoretical line because its values at nearby share almost all the same samples, and it plunges sharply whenever the error crosses zero. By contrast, the root-mean-square error averaged over 200 independent runs stays within about 20% of at every , falling steadily with slope across all four orders of magnitude.
24.5.2 Hypothesis Testing#
An error bar tells us how uncertain a single estimate is, but most decisions in machine learning compare two of them: did a new architecture, optimizer, or regularization trick actually beat the baseline? In this subsection, we first build a comparison test from scratch by simulation, then derive its closed-form counterpart, and finally ask how much data an experiment needs to reliably detect a real gain.
24.5.2.1 Comparison of Two Models#
Training a neural network is inherently random: weight initialization, data shuffling, and dropout masks all vary with the random seed, so running the exact same training script twice produces slightly different test accuracies. Suppose we train model A and model B across 20 seeds each and record their test accuracies. Imagine that seed-to-seed noise shifts a single run by roughly one percentage point, while model B is truly better by 0.8 percentage points. Given only those 40 numbers, can we tell that B is better? The natural summary is the difference between the two mean accuracies, which will serve as our test statistic.
Every hypothesis test begins by formulating the skeptical claim it tries to overturn. Here, the null hypothesis asserts that both lists of accuracies come from the same distribution, so the two models perform equally well on average. The alternative hypothesis asserts that their distributions differ. We then ask: if were true, how surprising would it be to see a gap at least as large as ours? If the gap would be very unlikely under chance alone, we reject ; otherwise, we fail to reject it. That asymmetric phrasing is deliberate: failing to reject does not prove the models are equal, just as a verdict of "not guilty" in court does not prove innocence.
24.5.2.2 The Permutation Test#
To judge whether an observed gap is surprising under , we need to know its distribution when holds, called the null distribution. Remarkably, we can construct this distribution directly from the data without assuming Gaussianity or any other parametric form, using a permutation test (Fisher, 1935). The logic is simple: if both lists truly came from the same distribution, then the labels "A" and "B" carry no information at all. Any reassignment of the 40 numbers into two groups of 20 would have been just as likely as the split we observed. By shuffling the labels, recomputing the mean gap, and repeating this times, we map out the range of gaps that pure chance produces. The helper below vectorizes all shuffles at once and counts how often a shuffled gap is at least as large in magnitude as the observed one.
def perm_p(acc_a, acc_b, rng, R=2000):
"""Two-sided permutation p-value and the R shuffled gaps."""
k = len(acc_a)
observed = acc_b.mean() - acc_a.mean()
pooled = np.tile(np.concatenate([acc_a, acc_b]), (R, 1))
shuffled = rng.permuted(pooled, axis=1) # R relabelings
gaps = shuffled[:, k:].mean(1) - shuffled[:, :k].mean(1)
p = (1 + (np.abs(gaps) >= abs(observed)).sum()) / (R + 1)
return p, gaps
Including the observed labeling as one of the shuffles yields the -value,
which estimates the probability, under , of observing a gap at least as extreme as the one we actually saw. A tiny -value means that such a large gap would rarely occur if the labels were meaningless. Notice that this -value is two-sided: large gaps in either direction count against . (If we asked only whether B beats A, a one-sided test would count only shuffled gaps at least as large as the observed positive gap.)
Before looking at the data, we commit to a significance level , conventionally , and agree to reject whenever . Let us run one simulated experiment with the numbers above to see the test in action.
k = 20 # training seeds per model
acc_a = rng.normal(0.850, 0.010, k) # per-seed accuracy, model A
acc_b = rng.normal(0.858, 0.010, k) # model B: a true gap of 0.008
p, gaps = perm_p(acc_a, acc_b, rng, R=10000)
observed = acc_b.mean() - acc_a.mean()
print(f'observed gap {observed:.4f}, permutation p-value {p:.3f}')observed gap 0.0044, permutation p-value 0.158
Because each experiment draws fresh seeds, the observed gap fluctuates around the true from run to run. In most runs, drops below and the test rejects , yet in a noticeable minority of runs it fails to reject, as may happen here. With a full percentage point of seed noise, 20 seeds per model are not always enough to catch a 0.8-point gain. Shortly, we will measure precisely how often this happens and see that it reflects the experiment's sample size rather than a defect in the test.
Plotting a histogram of the shuffled gaps alongside the observed gap (and its negative mirror image) lets us see the null distribution visually.
counts, edges = np.histogram(gaps, bins=50)
centers = (edges[:-1] + edges[1:]) / 2
top = counts.max()
d2l.plot([centers, [observed] * 2, [-observed] * 2],
[counts, [0, top], [0, top]], 'gap under label shuffling', 'count',
legend=['shuffled gaps', '±observed gap'],
fmts=('-', 'm--', 'm--'))Even though the permutation test assumed nothing about the shape of the data, the shuffled gaps settle into a neat bell curve centered at zero, with the observed gap typically landing out in one tail. Best of all, this exact same recipe works for any two-group summary statistic: a difference of medians, error rates, or validation losses. (When comparing means in closed form, its classical counterpart is Welch's -test.) Every hypothesis test follows the same discipline: state and , fix and choose a sample size large enough to detect a meaningful effect, and only then collect the data, compute the -value, and reject if .
24.5.2.3 The -Test#
While shuffling builds the null distribution empirically, assuming Gaussian data with a known variance gives us closed-form formulas for both the -value and the detection rate. Suppose are i.i.d. with known, and we wish to test . We standardize the sample mean by its standard error to form the test statistic
Under , , so follows a standard normal distribution. Write for the standard normal c.d.f. and for its -quantile, defined by (for instance, ). The two-sided -value is , so the condition is equivalent to . At , we reject whenever the sample mean lands more than standard errors away from . Figure 24.5.4 highlights these two rejection tails.
Rejection region of the two-sided -test at . Under , the standardized statistic follows a standard normal distribution: the central region holds probability , while the two tails beyond together hold . Observing a statistic in either tail would be rare under , so we reject .
Our two-model comparison has a direct two-sample version of this test. With independent seeds per model and per-seed standard deviation , the mean gap has variance , so is standard normal under . Plugging in and yields a standard error of for the gap. A true improvement of therefore sits standard errors above zero, past the threshold, though not by a comfortable margin.
24.5.2.4 Two Kinds of Error and Power#
Any hypothesis test can misfire in two ways, and good experimental design keeps both under control. A type I error (or false positive) occurs when we reject a true , claiming an improvement that does not exist. A type II error (or false negative) occurs when we fail to reject a false , missing a genuine improvement. Their probabilities are
where is evaluated at a specific alternative, such as a true gap of 0.8 percentage points. The complement is called the power of the test: the probability that the experiment actually detects that real effect. Figure 24.5.5 summarizes the four possible outcomes.
The decision matrix of a hypothesis test, showing correct decisions on the diagonal, type I error (rate ) and type II error (rate ) off the diagonal, and statistical power () in the correct-rejection cell.
Why does the simple rule "reject when " guarantee a type I error rate of exactly ? Because under , the -value is uniformly distributed on . This fact is worth proving: not only does it explain what a significance level means, it is also the key to understanding multiple testing later on.
Proposition (-values are uniform under the null). Let the test statistic have a continuous c.d.f. under , and let (one-sided) or (two-sided). Then for every .
Proof. We first show that is uniform on . For any , let be the largest value of satisfying ; such a value exists because is continuous and runs from to . Since is nondecreasing, holds if and only if , which gives . For the one-sided -value, it follows immediately that . For the two-sided -value, the event means either or ; these two disjoint events each have probability , so their union has probability .
For the permutation -value, an even simpler counting argument gives the same guarantee. Under , the observed labeling and the random shuffles are completely exchangeable, so the observed gap is equally likely to fall at any of the ranks. Consequently, happens only when the observed gap ranks among the largest in magnitude, yielding (ties can only increase ). That is why the in the numerator and denominator matters: it ensures that a level- test rejects a true null at most a fraction of the time.
What happens to the distribution of -values when is false? To see the contrast, let us simulate 2,000 two-sample -tests with 20 seeds per model, first with no true gap and then with our true gap of , and histogram the resulting -values into ten equal bins.
se = 0.010 * np.sqrt(2 / k) # se of the gap, k seeds per model
for gap in (0.0, 0.008):
acc_a = rng.normal(0.850, 0.010, (2000, k))
acc_b = rng.normal(0.850 + gap, 0.010, (2000, k))
T = (acc_b.mean(axis=1) - acc_a.mean(axis=1)) / se
p = 2 * norm.sf(np.abs(T)) # two-sided z-test p-values
hist = np.histogram(p, bins=10, range=(0, 1))[0] / 2000
print(f'gap {gap:.3f}:', ' '.join(f'{h:.2f}' for h in hist),
f' p <= 0.05: {np.mean(p <= 0.05):.2f}')gap 0.000: 0.10 0.10 0.11 0.10 0.09 0.10 0.10 0.10 0.10 0.10 p <= 0.05: 0.05
gap 0.008: 0.82 0.08 0.04 0.02 0.01 0.01 0.01 0.01 0.01 0.01 p <= 0.05: 0.72
When holds (gap ), the histogram is flat: roughly one-tenth of the -values fall in each bin, and about 5% land at or below . When there is a real gap of , the -values pile up sharply near zero: about 80% fall below , and 70% to 74% fall at or below . That rejection fraction is the power of the test, which our closed-form formula below predicts to be .
Before deriving that formula, it is worth guarding against two classic misreadings of a -value (Wasserstein and Lazar, 2016). First, a -value is the probability of seeing data at least this extreme assuming is true; it is not the probability that is true (which would require a prior and Bayes' rule). Second, a large -value does not prove that holds; it only tells us that the experiment failed to detect an effect, perhaps because it lacked the power to do so.
Let us compute that power explicitly for the one-sample -test. When the true mean is , the statistic is normal with mean and variance 1. Defining the standardized effect (the effect size measured in units of the noise), the test rejects whenever , which happens with probability
after dropping the negligible opposite tail . Thus power rises with the effect size and with . For a large effect , even observations give power .
In our two-sample model comparison, the statistic has mean with , so the -test power with seeds per model is : about with 20 seeds, and only with 5 seeds. Because that formula assumes we know in advance, let us check how the permutation test, which estimates nothing ahead of time, performs across 400 fresh simulated experiments for each seed budget.
def power(k, gap, rng, num_experiments=400):
"""Fraction of fresh experiments in which the permutation test rejects."""
rejections = 0
for _ in range(num_experiments):
acc_a = rng.normal(0.850, 0.010, k)
acc_b = rng.normal(0.850 + gap, 0.010, k)
rejections += perm_p(acc_a, acc_b, rng)[0] <= 0.05
return rejections / num_experiments
for k in (20, 5):
print(f'{k:2d} seeds: rejects in {power(k, 0.008, rng):.2f} of runs, '
f'formula {norm.cdf(0.8 * np.sqrt(k / 2) - 1.96):.2f}')20 seeds: rejects in 0.70 of runs, formula 0.72
5 seeds: rejects in 0.16 of runs, formula 0.24
Across 400 runs, the permutation test rejects in about 70% of experiments with 20 seeds and only about 20% with 5 seeds (each rate fluctuates by roughly two percentage points from run to run). Both numbers sit slightly below the -test formula because the permutation test effectively estimates the noise from the data, which costs a small amount of power. Even with 20 seeds, then, our experiment misses a genuine 0.8-point gain roughly three times in ten; with only 5 seeds, it misses four times in five. Failing to reject with a power of tells us almost nothing. In practice, experimenters typically aim for a power of at least .
24.5.2.5 Sample Size#
Rather than discovering after the fact that an experiment was underpowered, we can plan the sample size up front. Setting the power formula equal to gives , and solving for yields the sample size needed to detect a standardized effect at significance level with power :
Notice the steep scaling: cutting the target effect size in half requires four times as much data. For the standard benchmark of and power , we have and , which simplifies to the handy rule of thumb . Figure 24.5.6 plots the resulting power curves across effect sizes.
Power of the two-sided -test at versus sample size , with one curve per standardized effect . Each curve starts near (dotted line), where the test rejects only by chance, and climbs toward . The dashed line marks the power target, reached at : about 8 observations for , rising to about 78,500 for .
When comparing two independent groups of observations each with common standard deviation , the variance of the difference doubles to . Accordingly, the required sample size per group doubles as well:
For our model comparison with , reaching 80% power requires seeds per model, which explains why 20 seeds fell just shy of the mark.
24.5.2.6 Paired Comparisons#
Let us now return to our opening puzzle: two classifiers that scored 912 and 921 out of 1,000. Earlier we noted that treating their scores as independent left the gap buried in noise. Crucially, though, both models answered the same 1,000 questions. Some questions are easy for both models and others are hard for both, and an unpaired analysis lumps all of that shared question difficulty into the noise.
A paired comparison strips out that shared variation by working directly with the per-question differences , defined as model B's correctness minus model A's on question . Whenever both models agree, . Suppose they disagree on 41 questions: model B alone is right on 25, and model A alone is right on 16, giving the net lead of (0.9 percentage points). Under the null hypothesis that the two models are interchangeable, each disagreement is like a fair coin flip, equally likely to favor A or B. The appropriate null simulation therefore flips the sign of each nonzero at random, a procedure known as the sign-flip permutation test. Let us run it on these 41 disagreements.
d = np.r_[np.ones(25), -np.ones(16), np.zeros(959)] # B only, A only, agree
nonzero = d[d != 0] # agreements never change
signs = rng.choice([-1, 1], size=(100000, len(nonzero)))
flipped = (signs * nonzero).sum(axis=1) / len(d) # gaps under H_0
p = (1 + (np.abs(flipped) >= abs(d.mean())).sum()) / (len(flipped) + 1)
print(f'gap {d.mean():.3f}, sign-flip p-value {p:.2f}')
gap 0.009, sign-flip p-value 0.21
The sign-flip test returns (replacing random sign flips with the exact binomial probability gives McNemar's test). Compare this with an unpaired analysis of the exact same counts, which yields a gap of only standard errors and . Pairing cuts the standard error of the gap in half, from down to , because the 959 questions on which the models agree no longer inject noise. Even so, a 25-to-16 split among 41 disagreements is still too small to be convincing: a nine-question margin on a 1,000-question test does not establish that model B is better.
Pairing matters most when you design an evaluation from scratch. Suppose two models have true accuracies of 90% and 91% and disagree on 4% of questions (B alone right on 2.5%, A alone on 1.5%). Then has mean and variance , giving a standardized effect of . By (24.5.9), a paired test reaches 80% power with about questions. By contrast, evaluating the two models on separate, independent test sets leaves an unpaired variance of per pair of questions, requiring roughly questions per model.
In this example, pairing shrinks each test set by more than a factor of four and reduces total labeling effort by nearly a factor of nine, and the savings grow even larger when the two models agree more frequently. The practical rule is clear: always evaluate competing models on the same test set and analyze the per-question differences. The same principle applies to random seeds: when two models share the same training seeds, flip the signs of the per-seed differences (exercise 5).
24.5.2.7 Multiple Testing#
Every significance guarantee so far, , assumes we run a single test chosen in advance. In machine learning, however, hyperparameter sweeps routinely run dozens of comparisons at once. Suppose you compare 20 new configurations against a baseline when none of them is actually better, testing each at . If the tests are independent, the probability that at least one configuration falsely looks significant is . Cherry-picking only the winners, or repeatedly tweaking an analysis until (-hacking), reliably turns pure noise into publishable-looking gains.
The simplest safeguard is the Bonferroni correction (Bonferroni, 1936): when running tests, lower each individual threshold to . Writing for the event that test falsely rejects a true null, the union bound gives
Notice how remarkably general this bound is: it caps the probability of making any false discovery at without assuming anything about how the tests are correlated. For 20 independent tests run at , the chance of at least one false positive drops from to .
Unfortunately, when reaches the hundreds or thousands, dividing by makes the Bonferroni threshold so strict that genuine discoveries get buried. In large-scale screening, statisticians instead control the false discovery rate, the expected fraction of false positives among the hypotheses we reject. The Benjamini–Hochberg procedure (Benjamini and Hochberg, 1995) keeps this rate at or below whenever the -values are independent or positively dependent; exercise 2 introduces the rule and tests it in simulation.
24.5.3 Confidence Intervals#
A -value answers a binary question about a single candidate parameter value. In practice, we usually want more: the entire range of parameter values consistent with the data, reported directly as an error bar around our estimate.
24.5.3.1 Definition and Interpretation#
A confidence interval is produced by a rule guaranteed to capture the fixed, unknown parameter in a specified fraction of repeated experiments (Neyman, 1937). Formally, a confidence interval is a random interval , computed from the data, satisfying
We deliberately write rather than to emphasize where the randomness sits: is a fixed number, while the interval shifts from one data set to the next. The probability is a property of the procedure. Across many independent experiments, at least 95% of the resulting 95% confidence intervals will cover . Any single interval you compute either contains or misses it, and the interval itself carries no hint of which happened. Figure 24.5.7 illustrates this with 100 intervals drawn from 100 independent samples. Many intervals used in practice satisfy this guarantee only in the large-sample limit: an asymptotic interval satisfies for every .
One hundred 95% confidence intervals, each constructed from its own independent sample, plotted against the fixed true mean (dashed line). Most intervals cover the truth while the orange ones miss. The 95% guarantee describes the long-run hit rate of the procedure; an individual interval gives no sign of whether it succeeded.
24.5.3.2 The Gaussian Interval#
Let us start with the cleanest case, where every step is exact. Suppose are i.i.d. with known. Because , setting the half-width to ensures that lands within of with probability . Now flip that inequality around so it reads as a statement about :
Hence for every . That simple algebraic reversal is the entire idea behind a confidence interval. At , the interval is .
In real problems is rarely known, so we substitute the sample standard deviation from (24.5.3). Once is estimated from the data, the studentized statistic is no longer normal. For Gaussian data, it follows Student's distribution with degrees of freedom (Student (Gosset, 1908), which has heavier tails than the normal distribution to account for the extra randomness in . (We take this distribution on faith here; exercise 4 derives it as a Gaussian with random precision.) Replacing by the -quantile yields
which achieves coverage for Gaussian data at every . At small sample sizes, this distinction matters enormously: is for , for , and for , converging toward as grows. The workhorse interval used throughout applied work simply plugs in the large-sample limit,
an asymptotic 95% interval that is slightly too narrow at every finite . For Gaussian data, its actual coverage is , which is close to nominal at () but drops to at .
What if the data are not Gaussian? By the central limit theorem (Section 24.3.2.3), converges to a standard normal whenever the variance is finite, and converges to by the law of large numbers. Consequently, (24.5.13) remains an asymptotic 95% interval for the mean of any distribution with finite variance. How large needs to be depends on the shape of the data: skewed distributions need more samples (exercise 3), and accuracies close to 100% need far more, since many test sets produce a perfect score with zero sample variance (exercise 4). In all cases, the half-width scales as , so cutting an error bar in half takes four times the data.
Because a test accuracy is the mean of 0/1 indicators with , the same formula gives , known as the Wald interval. Let us evaluate it for our 1,000-question classifier and for our running coin example (9 heads in 13 flips).
for n_correct, n in ((912, 1000), (9, 13)):
theta_hat = n_correct / n
half = 1.96 * np.sqrt(theta_hat * (1 - theta_hat) / n)
print(f'{n_correct:3d} of {n:4d}: '
f'({theta_hat - half:.3f}, {theta_hat + half:.3f})')
912 of 1000: (0.894, 0.930)
9 of 13: (0.441, 0.943)
For the classifier, we obtain percentage points. For the coin, the interval comfortably includes , confirming that 13 flips are far too few to conclude the coin is biased. Pinning its bias down to would take roughly flips.
It is illuminating to contrast this with a Bayesian credible interval for the same coin. A Bayesian analysis treats itself as random, puts a prior on it, and reports an interval containing posterior probability given the observed flips. With a uniform prior, the posterior is (Section 24.4), whose central 95% credible interval (between the 2.5% and 97.5% posterior quantiles) is . Although the numbers look similar here, the two intervals make fundamentally different claims. The credible interval says that, under the chosen prior, lies in with probability . The confidence interval says that its construction procedure traps the fixed true in at least 95% of repeated experiments, regardless of what is. Keep in mind, too, that the Wald interval meets its guarantee only asymptotically: with 13 flips, its actual coverage is around 91% at and drops below 50% at .
Because coverage is a frequency across repeated experiments, we can test it directly by simulation. Let us draw 1,000 independent data sets of standard normal observations, compute the asymptotic interval (24.5.13) on each, and count how many cover the true mean .
mu, n, trials = 0.0, 100, 1000
data = rng.normal(mu, 1.0, (trials, n)) # one row = one data set
mu_hat = data.mean(axis=1)
se = data.std(axis=1, ddof=1) / np.sqrt(n)
hits = np.abs(mu_hat - mu) <= 1.96 * se # does the interval contain mu?
print(f'first interval ({mu_hat[0] - 1.96 * se[0]:.3f}, '
f'{mu_hat[0] + 1.96 * se[0]:.3f}) contains 0: {hits[0]}')
print(f'{hits.sum()} of {trials} intervals contain the true mean '
f'(nominal 950, exact 947)')first interval (-0.299, 0.098) contains 0: True
951 of 1000 intervals contain the true mean (nominal 950, exact 947)
The first interval covers in about 95% of runs, and the total hit count centers around 947 (typically within ) rather than 950. That three-hit shortfall is not random noise. At , the exact -quantile is instead of , so the true coverage of the 1.96 interval is . The scatter around 947 is simply two binomial standard deviations, . This same recipe gives the error bar on a mean accuracy across training seeds: take the seed-to-seed standard deviation divided by , and multiply by the appropriate quantile.
24.5.3.3 Tests and Intervals#
You may have noticed that the number just appeared twice: once as the rejection threshold of the -test, and again as the multiplier in the Gaussian confidence interval. That is no coincidence; tests and confidence intervals are two sides of the exact same coin.
Consider Gaussian data with known . A two-sided -test of fails to reject precisely when , where . Rearranging that inequality gives with , which simply states that . In short, a 95% confidence interval is the set of null values that a 5% hypothesis test keeps. Its coverage guarantee follows immediately from the test's type I error rate: for every , .
What makes this duality so useful is that it works for any family of hypothesis tests. If for every candidate we have a level- test of , then collecting all values that the test does not reject automatically forms a confidence set by the same one-line argument. Whenever an explicit formula fails or misbehaves, we can invert a test instead. For example, if a model answers 29 of 30 questions correctly, the Wald interval absurdly extends past an accuracy of , whereas inverting an exact binomial test produces a valid interval inside (exercise 4).
This duality also suggests a better habit when comparing two models: report a confidence interval for the difference, such as across seeds. It excludes if and only if the hypothesis test rejects, while also showing you how large the improvement might actually be.
24.5.3.4 The Delta Method#
Often we care not about itself, but about a smooth function of it: the log-odds of an accuracy, the ratio of two losses, or a relative error reduction. How do we propagate our error bar through ? When is differentiable at , a first-order Taylor expansion gives
Locally around , the function simply rescales small deviations by its slope . Taking standard deviations and plugging in for the unknown in yields the delta method (Wasserman, 2013):
Let us try it on a concrete number. An accuracy of on questions has standard error . Its log-odds has derivative , so the standard error of the log-odds is roughly .
The same linearization extends directly to a vector of estimates with covariance matrix , giving . Notice that the off-diagonal covariances in matter: if you take the ratio of two losses measured on the same test set, the numerator and denominator fluctuate together.
Like any linear approximation, the delta method has clear limits. First, it requires : at a stationary point such as evaluated at , the linear term vanishes and fluctuates at the faster rate rather than . Second, must stay inside a region where is nearly linear, which breaks down for an accuracy very close to 100% (exercise 4). And when a statistic has no handy derivative at all, we need a completely different approach: resampling.
24.5.4 The Bootstrap#
Every standard error we have computed so far came from an analytic formula. Yet many quantities we care about in practice, such as a sample median, an AUC, or a BLEU score, fluctuate from test set to test set just like accuracy does, without offering a tidy formula for their variance. The bootstrap solves this by simulating the sampling distribution directly from the data. Below, we first verify the method on a case whose answer we know, then apply it where no simple formula is available, and finally examine two instructive ways it can fail.
24.5.4.1 The Plug-in Principle#
If we knew the true data-generating distribution , finding the sampling distribution of any statistic would be effortless: just draw thousands of fresh data sets from and recompute the statistic on each. Of course, we do not know . The bootstrap (Efron, 1979) makes one bold substitution: it replaces the unknown with the empirical distribution , which places probability on each of the observed data points. Drawing a new sample of size from is simply sampling points from our data with replacement. The entire algorithm takes three steps:
- Draw points from the observed sample with replacement to create a bootstrap resample (some original points appear multiple times, others not at all).
- Recompute the statistic on that resample.
- Repeat times to collect replicates .
The standard deviation of those replicates estimates , and their and quantiles form the percentile confidence interval. Figure 24.5.8 illustrates the workflow. Behind its simplicity lie two key assumptions: the observations are i.i.d., and the statistic varies smoothly under small perturbations of the data.
The ordinary bootstrap. Starting from one observed sample (top left), we draw many resamples of the same size with replacement (bottom left, where tick heights count how many times each observation was selected) and recompute the statistic, here the median. The histogram of replicates (right) approximates the sampling distribution around (dashed line): its standard deviation estimates the standard error, and its central quantiles form a percentile interval. The histogram looks jagged because any resample's median must equal one of a few observed values; this mild lumpiness turns into outright failure for the maximum.
24.5.4.2 Bootstrap Standard Errors#
Before trusting the bootstrap on a hard statistic, let us check it against a formula we already know. Our opening test set had 912 correct and 88 incorrect answers, with theoretical standard error . Let us resample those 1,000 binary indicators 5,000 times and see if the bootstrap recovers the same number.
correct = np.r_[np.ones(912), np.zeros(88)] # the opening's test set
idx = rng.integers(0, len(correct), (5000, len(correct))) # 5,000 resamples
boot = correct[idx].mean(axis=1) # accuracy of each resample
print(f'bootstrap se {boot.std(ddof=1):.4f}, '
f'formula {np.sqrt(0.912 * 0.088 / 1000):.4f}')bootstrap se 0.0090, formula 0.0090
The two estimates match to within a few percent. Now let us turn to a statistic without a practical closed-form standard error: the median of 200 draws from the exponential distribution with mean 1, a right-skewed distribution whose true median sits below its mean. An asymptotic formula for the median's standard error does exist, namely , where is the density evaluated at the median (exercise 6), but in real life we do not know . In our synthetic experiment we do know it, , giving a theoretical benchmark of against which we can judge the bootstrap.
data = rng.exponential(1.0, 200) # its median's se formula needs the unknown density
theta_hat = np.median(data)
idx = rng.integers(0, len(data), (10000, len(data))) # resample with replacement
boot = np.median(data[idx], axis=1) # one median per resample
lo, hi = np.percentile(boot, [2.5, 97.5])
print(f'median {theta_hat:.3f}, bootstrap se {boot.std(ddof=1):.3f}, '
f'95% percentile interval ({lo:.3f}, {hi:.3f})')median 0.741, bootstrap se 0.090, 95% percentile interval (0.636, 0.993)
Without ever being told the density, the bootstrap typically lands near . Across different data sets, the sample median fluctuates around (usually within ), and the bootstrap standard error itself varies between roughly and . Why so much variation? Because the median of any resample must equal one of the few original data points sitting near the middle of the sample, making the bootstrap distribution lumpy and sensitive to the random gaps between those points. Consequently, the percentile interval is somewhat coarse and occasionally barely covers . Even so, the median is smooth enough for the bootstrap to remain valid, since the underlying density at the median is strictly positive.
24.5.4.3 Failures of the Bootstrap#
It is just as important to know when the bootstrap breaks. Both of its core assumptions, smoothness and independence, can fail in practice.
First, the bootstrap fails when a statistic depends too sharply on extreme data points. The classic counterexample is the sample maximum. Let be i.i.d. uniform on , with estimator . Any bootstrap resample achieves the exact same maximum unless all draws happen to miss the single largest observation, which gives
Thus, the bootstrap distribution piles 63% of its probability mass onto a single point, even though the true sampling distribution of is continuous. Worse still, no resample can ever exceed , which is strictly below , so the percentile interval has zero chance of containing .
Second, the bootstrap fails when you resample units that are not independent, a common trap in modern NLP and vision benchmarks. Consider a reading-comprehension benchmark containing passages with questions per passage. If a model misunderstands a passage, it tends to miss several of its questions at once. Suppose correctness indicators for two questions on the same passage have correlation , while different passages are independent. Then the overall accuracy has variance
which is inflated by a factor of compared with independent questions. A naive bootstrap that resamples individual questions ignores this within-passage correlation and understates the standard error by . Even at and a modest correlation of , that understates the error bar by a factor of (Miller, 2024). The fix is straightforward: resample whole passages instead of individual questions (exercise 8).
We end this section with two important questions left open. First, we have studied how to evaluate and put error bars on a given estimator, but we have not yet asked how to construct a good estimator in the first place, or how tightly any estimator can pin down a parameter; Section 24.6 answers both questions through the likelihood function and its curvature. Second, every guarantee in this section assumed a single estimator or hypothesis test fixed before seeing the data. A model chosen because it achieved the highest score on a validation set does not satisfy that assumption: picking the winner from many candidates is multiple testing in disguise. In Section 24.10, we will ask how large a sample we need for our guarantees to hold simultaneously across an entire family of models.
24.5.5 Summary#
Any number computed from random data is itself a random variable, and its sampling distribution across hypothetical alternative data sets determines how far we can trust it. Because mean squared error splits into squared bias plus variance, a biased estimator such as the shrunk mean can outperform the unbiased sample mean. Viewing an integral as an expectation turns the sample mean into Monte Carlo estimation, whose error rate never degrades with dimension, unlike deterministic grids. A hypothesis test rejects the null hypothesis when an observed difference would be rare by chance; since a -value is uniform under the null, rejecting when controls the false-positive rate at , while statistical power grows with the standardized effect times and increases dramatically when competing models are paired on the same questions. A confidence interval is simply the set of parameter values that a hypothesis test fails to reject. Finally, when no analytic standard error exists, the bootstrap simulates the sampling distribution by resampling the data, working well for smooth statistics of independent observations while breaking down for extremes like the maximum and for clustered test sets.
24.5.6 Exercises#
-
[code] Shrinking the sample mean. The text found that the shrunk mean of i.i.d. has the smallest MSE at .
- Extend the text's simulation of the sample mean, the shrunk mean
and the median to a grid of factors at
, and . Plot the squared bias, the
variance and the MSE against with
d2l.plot, and compare the empirical minimizer with . - Shrink toward a point instead of , with the estimator . Compute its MSE and its optimal factor. Which would you choose, and what does the answer say about the choice of in the text?
- is not an estimator, because it contains . Plug in for and for , giving , and measure the MSE of by simulation at . Where does it beat , and where does it lose? Exercise 9 shows that in three or more dimensions a similar substitution wins for every .
Hint for (c): at the plug-in factor is itself noisy; look at its distribution.
- Extend the text's simulation of the sample mean, the shrunk mean
and the median to a grid of factors at
, and . Plot the squared bias, the
variance and the MSE against with
-
[code] Multiple comparisons. A hyperparameter sweep compares many configurations with one baseline, so it runs many tests at once.
- Twenty models, none of them better than the baseline, are each compared with it by an independent test at . Compute the probability that at least one comparison is significant, and the same probability at the Bonferroni threshold . Show that the Bonferroni correction holds the probability of at least one false positive at or below even when the tests are dependent.
- The Benjamini–Hochberg procedure (Benjamini and Hochberg, 1995)
sorts the -values, , finds the
largest with , and rejects the
hypotheses with the smallest -values. Simulate a sweep of
configurations, of which have no effect. Draw the
-statistics from for these and from
for the other , and compute the two-sided
-values
2 * norm.sf(np.abs(z)). Over repetitions, report the average numbers of true and false discoveries and the average false-discovery proportion (the fraction of rejections that are false, or without rejections) for the uncorrected threshold , for Bonferroni and for Benjamini–Hochberg. For independent tests, Benjamini–Hochberg guarantees an expected false-discovery proportion of at most . Does the simulation agree?
-
[code] Coverage at small . The interval (24.5.13) uses the Gaussian quantile in place of the -quantile, and it assumes approximately Gaussian sample means.
- Run the coverage simulation of the text (1,000 intervals from standard normal data sets) with and trials, and record the coverage of the interval. Then replace by the quantile of the -distribution with degrees of freedom, which is , , , and for these , and record the coverage again.
- Set and replace by , the quantile of the -distribution with one degree of freedom, so that the interval has coverage. Compute the coverage separately for the intervals shorter and longer than the median width. Does the difference contradict (24.5.11)? Would you read a short interval as a sign of a precise estimate?
- Draw the data from the exponential distribution with mean at , keeping the -quantile . Measure the coverage, and count separately the intervals that lie entirely below and entirely above the true mean. Explain the asymmetry from the shape of the distribution.
-
[code] Delta method near a boundary. By (24.5.14), an accuracy measured on test examples has a log-odds with standard error about .
- Simulate test sets by drawing the number of correct predictions from the binomial distribution with and . Compare the standard deviation of the log-odds with the delta-method value.
- Repeat with . Estimate the fraction of test sets with , compare it with its exact value, and state the log-odds of such a test set.
- Which assumption behind the first-order expansion fails at ? Compute the expected number of incorrect answers, , for both values of , and explain why this count, rather than alone, decides whether the delta method and the Wald interval can be trusted.
- A benchmark has 30 questions, and a model answers 29 of them correctly. Compute the Wald interval and note where it ends. Then invert a test: for each on a fine grid of , compute the exact two-sided -value of , with , and collect the that it keeps at . Compare the two intervals, and their coverage at over simulated benchmarks.
-
[code] Paired comparisons. ● Two models evaluated on the same test examples or the same seeds share part of their noise, and a paired test removes it.
- In the text the two models disagree on 41 questions, 25 to 16. Under the number of questions that only B gets right is . Compute the exact two-sided -value and compare it with the Monte Carlo value of the sign-flip cell in Section 24.5.2.6. Then fix the net gap at 9 and vary the number of disagreements: compute for 9 to 0, 17 to 8, 25 to 16 and 55 to 46. What decides the verdict, the gap or the number of disagreements?
- Model the per-seed accuracies with a seed effect that both models
share: for seed , the accuracies are and
, where and
are independent. Implement
the sign-flip test on the per-seed differences as an exact test:
with seeds, enumerate all sign patterns instead of drawing
random ones. Over experiments with seeds, compare its
power with that of the unpaired permutation test
perm_p. - Repeat with seeds. What is the smallest two-sided -value that
the exact sign-flip test can return, and what does it imply at
? A Monte Carlo version that draws random sign
patterns, as
perm_pdraws random shuffles, rejects in a few percent of these experiments. Why?
-
Standard error of the median. ● Let be i.i.d. with c.d.f. , median , and density at the median. The sample median is at most exactly when at least half of the observations are at most .
- The empirical c.d.f. has mean and variance . Use the central limit theorem to show that for small , and conclude that . Relate the factor to the slope in (24.5.14).
- Evaluate the approximation for the exponential distribution with mean at , and compare it with the bootstrap standard error that your run of the text's bootstrap of the median prints. Rerun the cell several times: the printed value moves between about and . Why does the bootstrap estimate of a median's standard error vary this much from data set to data set, when the bootstrap estimate of a mean's standard error does not?
- Compute the ratio for large for Gaussian data and for Laplace data. Which estimator of the location would you choose for heavy-tailed data?
Hint for (b): a resample's median is one of a few observed values near , and the spacing of those values is random.
-
[code] Grids against Monte Carlo. ● Section 24.5.1.7 compares exponents: with evaluations in dimensions, a second-order grid has error of order and Monte Carlo of order . Test this comparison on over , whose integral is by Fubini's product rule (Section 22.6).
- Implement the midpoint rule on the full grid of cubes and the Monte Carlo average (24.5.7) over uniform samples. For and up to about , plot the relative error against on log-log axes, using for Monte Carlo the root mean squared error over repetitions. Do the slopes match the predicted exponents?
- At the exponents tie. Which method is more accurate there? What sets the constant in front of each rate, and how does each constant change with ?
- Both errors can be predicted. The midpoint sum of is a product of one-dimensional midpoint sums. The root mean squared error of Monte Carlo is by (24.5.8), for uniform on , and the product rule factors into one-dimensional integrals. Compute both predicted relative errors for at and compare them with your measurements. At which do the two methods break even? How reliably do repetitions decide the comparison at that ?
-
[code] Clustered test sets. ● Evaluation sets often consist of clusters of related items, such as several questions about one passage, and the i.i.d. bootstrap then understates the standard error (Miller, 2024). A test set has clusters of items each, its expected accuracy is , the correctness indicators of two items in the same cluster have correlation , and items in different clusters are independent.
- Show that the average of variables with common variance and pairwise correlation has variance , and conclude that the accuracy on the test set has variance
- Simulate and , drawing a cluster accuracy for each cluster and conditionally independent items given . These choices give and . Over test sets, compare the standard deviation of with the average i.i.d. bootstrap standard error, which resamples items as in the text's bootstrap of the accuracy, and with the average cluster bootstrap standard error, which resamples whole clusters, using resamples for each. By which factor does the i.i.d. bootstrap understate the standard error? Compare the factor with the prediction of (a).
- [code] Stein's paradox. ●● Observe and measure an estimator by its risk , the MSE with squares replaced by squared norms. The estimator has risk for every . James and Stein (1961) showed that for the estimator
has smaller risk for every .
- Prove Stein's lemma (Stein, 1981): if and is differentiable with , then . Integrate by parts.
- For an estimator with weakly differentiable (here: differentiable away from the origin, with ), show that its risk is
Use this identity to show that has risk . Where does the argument need ?
- Simulate the risks of , of , and of the positive-part estimator for and , and plot them against .
- Write the optimal factor for in dimensions, the analogue of the text's . Which function of the data replaces the unknown quantity in , and why does this substitute become accurate as grows? Compare with exercise 1c.
- [extended] Peeking at a running test. ●● An A/B test, or an
evaluation during training, is often watched while the data arrive and
stopped as soon as the result looks significant
(Johari et al., 2017). Let be i.i.d.
, let , and let .
The -test at time rejects when .
- Simulate runs of length under . Estimate the probability that at least one of equally spaced looks rejects, for . The law of the iterated logarithm implies that this probability tends to one as monitoring continues indefinitely. How fast does it grow in your table?
- Put the prior on and define the mixture likelihood ratio
Show that , and that under it is a martingale: .
- Ville's inequality, which we take on faith, states that a nonnegative martingale with satisfies . Conclude that rejecting at the first with has type I error at most , however often the data are inspected. Derive the rejection boundary for , and compare its growth in with that of the fixed boundary .
- Check the type I error of the sequential test by simulation for . Then set , and take the fixed-sample -test whose follows from (24.5.9) for power as the reference. For each of the three values of , report the power of the sequential test by that , its median stopping time, and its power by . How does the choice of affect these numbers? What does a test that is valid at every look give up, and what does it gain?