Applied review: a benchmark metric is an estimator
A dense review of m05 inference applied to model evaluation: test accuracy as a sample mean with standard error, clustered errors for grouped items, minimum detectable difference determined by test size, and varying meanings of ±. This prepares the ML statistical significance lessons.
After this lesson you can
- Calculate standard error and a Wilson interval for test accuracy.
- Calculate clustered standard errors when benchmark items are dependent.
- Calculate minimum detectable difference for a benchmark of size n, with and without pairing.
- Interpret and report seed standard deviations, standard errors, and confidence intervals unambiguously.
Before you start
A score is not a universal constant
A classifier answers 820 of 1000 questions correctly. Its observed accuracy is exactly 0.82 for that list and model. If the list were a random sample from a question population, it would also estimate accuracy in that population. The two statements answer different questions: the first needs no sampling interval, the second does. An interval does not correct a biased list or automatically make its questions representative.
Another experiment is possible: repeat training with different seeds and evaluate each model on the same list. Dispersion across seeds describes that randomness, conditional on the list. Changing training data or split changes variation sources too. The experimental unit and sources of variation belong in the report, not just the code.
Marginal bars can overlap even when a paired difference is precise: shared noise cancels on subtraction. They can also fail to overlap under one convention and overlap under another. To decide about a difference, calculate its interval directly. A standard-deviation bar is not a confidence interval, and visually comparing overlap of two marginal intervals is not a paired test.
From counts to an interval
The sampling distribution is the distribution of the statistic over hypothetical samples, not the distribution of observed . Since and independence eliminates covariances, . The plug-in estimated standard error is . For 820 of 1000 it is 0.01215, or 1.215 percentage points. This is uncertainty about the mean, not the standard deviation of individual correct answers.
The central limit theorem motivates a normal approximation when enough independent observations exist and the distribution is not too close to a boundary. The Wald interval can perform poorly near 0 or 1 and even leave the probability range. Inverting the score test yields the Wilson interval. With , its endpoints are
For 820/1000, 95% Wilson is approximately [0.79498, 0.84257]. Coverage is a property of a repeated procedure under the model, not the posterior probability that the fixed parameter lies in this particular interval. Wilson is approximate and does not guarantee exactly 95% for every . Its derivation and formula are described by NIST. Miller explicitly treats evaluation questions as a sample from a superpopulation; validity of that abstraction still depends on sampling design.
Two random sources, two questions
With a fixed model, resampling items estimates variation over the item population. With a fixed test and retrained models, deviation across seeds estimates training-procedure dispersion conditional on the test. Neither alone measures the other. Generalizing across both needs a design allowing both sources to vary and an appropriate analysis, such as the next lesson’s hierarchical bootstrap. Reusing questions for every seed creates dependence between scores: do not turn seed-by-item results into independent observations.
Deterministic training does not remove test-sampling uncertainty. Conversely, an exhaustive test of a particular finite population does not remove variation across retrained models. Before calculating a bar, write what could be repeated and the universe about which you want to conclude.
Questions sharing a document
Ten questions about the same passage may be easy or hard together. Treating 1000 questions grouped in 100 documents as 1000 independent units often underestimates error when positive within-document correlation exists. Clustered standard error first sums residuals within each group and treats groups, not items, as independent.
Let be the number of documents, the total number of questions, and . A sandwich estimator for the question-weighted mean, with finite-group correction, is
The estimand weights every question equally. If the average document matters, first calculate a mean per document and change the estimand. With one item per group, the expression exactly equals sample deviation divided by . With few groups, dominant groups, or dependence across documents, normal approximation may cover poorly; multiplying by a correction is insufficient. Use enough groups and consider an interval suited to few groups.
For constant group size and common intragroup correlation , mean variance is multiplied relative to independence by . This is the design effect. It follows from counting variances and covariances per group. With unequal sizes or varying correlations this simple formula is not exact. Positive correlation reduces effective sample size; admissible negative correlation can have the opposite effect.
The simulation repeats 500 benchmarks per setting, so observed coverage also has Monte Carlo error. For example, coverage near 95% has simulation standard error near one percentage point. The generator mixes documents with common answers and documents with independent answers; with mixture probability , its intragroup correlation is precisely . Changing group count changes both information and approximation quality.
What difference can be detected?
The minimum detectable difference (MDD) is an effect size for which a planned test reaches target power under specific assumptions. Power is the probability of rejecting the null when a given alternative holds; effect size determines that alternative. An MDD is neither a threshold below which an effect is impossible nor a guarantee for one sample.
For two proportions near , with items per model, a two-sided test at level , and approximate power , we obtain
Here is correlation between A and B correctness on the same item; for independent samples use zero. The calculation approximates variance under null and alternative with the same base accuracy and uses a dominant tail of the two-sided alternative. Correlation must be compatible with binary marginals. A large effect may change those marginals and require an exact calculation or specific simulation. A clustered benchmark also requires modeling dependence across items. Sample-size planning inverts the same relation: halving MDD requires approximately quadrupling if other assumptions hold.
Pairing’s reduction appears by expanding variance of . If both marginals have variance and correlation , then . For independent pairs, mean variance is that quantity divided by . Models need not have identical accuracy to calculate empirical variance of differences; equal marginals serve only this approximate planning formula.
High correlation implies many shared successes and failures, so common noise disappears on subtraction. But arbitrary correlation cannot be imposed while keeping two binary proportions fixed: joint probabilities must be nonnegative. Also, if the test sample is fixed and the scientific question concerns training seeds, per-item correctness correlation does not describe seed variation.
With , , , power 0.8, and independent samples, the result is 0.03544, or 3.54 percentage points. One percentage point is 0.01, not 1% of base accuracy. Card and colleagues study power in NLP evaluation and note underpowered-study risk; this simple calculation does not reproduce their BLEU analyses or data.
What the ± sign communicates
The error-bar convention must name the quantity, number and type of units, and procedure. With independent seeds and sample deviation , describes dispersion of individual results, while estimates standard error of their mean. A t interval for the mean is under independent normal scores; with few seeds normality can be hard to assess. A paired difference uses deviation of differences, not the sum of each method’s bars.
A reproducible table might say “mean of 10 trainings, ± standard deviation across seeds, fixed test; paired B−A difference and its 95% t interval”. For a bootstrap interval, specify unit and resampling method. “85.1 ± 0.3” without these details cannot reconstruct uncertainty, comparison, or variation source. Rounding endpoints before testing can change a near-threshold decision: retain internal precision.
Lab: estimators from scratch
These functions are self-contained: you can copy them to researchkit.py. Scores are treated as finite numeric observations. Group correction assumes independent groups; Wilson assumes independent Bernoulli observations. The paired formula accepts general per-example scores, not just correctness. Run cells in order.
import numpy as np
from scipy.stats import norm
def naive_se(scores):
x = np.asarray(scores, float)
if x.ndim != 1 or len(x) < 2 or not np.isfinite(x).all():
raise ValueError('Se necesitan dos observaciones finitas')
return float(x.std(ddof=1) / np.sqrt(len(x)))
def clustered_se(scores, ids):
x, ids = np.asarray(scores, float), np.asarray(ids)
if x.ndim != 1 or ids.ndim != 1 or len(x) != len(ids) or not np.isfinite(x).all():
raise ValueError('Datos incompatibles')
_, inv = np.unique(ids, return_inverse=True)
g = len(np.unique(ids))
if g < 2: raise ValueError('Se necesitan dos grupos')
sums = np.bincount(inv, weights=x-x.mean(), minlength=g)
return float(np.sqrt(g/(g-1)*np.sum(sums**2))/len(x))
def paired_se(a, b):
a, b = np.asarray(a, float), np.asarray(b, float)
if a.shape != b.shape: raise ValueError('Parejas incompletas')
return naive_se(a-b)
def wilson_interval(k, n, alpha=.05):
if not isinstance(n, int) or isinstance(n, bool) or not isinstance(k, int) or isinstance(k, bool) or n < 1 or not 0 <= k <= n or not 0 < alpha < 1:
raise ValueError('Conteos o nivel inválidos')
p=k/n; z=norm.ppf(1-alpha/2); den=1+z*z/n
center=(p+z*z/(2*n))/den
half=z*np.sqrt(p*(1-p)/n+z*z/(4*n*n))/den
return center-half, center+half
def mdd(p, n, alpha=.05, power=.8, rho=0):
if not 0 < p < 1 or not isinstance(n, int) or isinstance(n, bool) or n < 1 or not 0 < alpha < 1 or not .5 < power < 1:
raise ValueError('Parámetros inválidos')
lower=-min(p/(1-p),(1-p)/p)
if not lower <= rho <= 1: raise ValueError('Correlación incompatible')
return float((norm.ppf(1-alpha/2)+norm.ppf(power))*np.sqrt(2*p*(1-p)*(1-rho)/n))
x=np.r_[np.ones(820),np.zeros(180)]
print('SE binomial por sustitución:', np.sqrt(.82*.18/1000))
print('SE muestral ddof=1:', naive_se(x))
print('Wilson:', wilson_interval(820,1000))
print('MDD independiente:', mdd(.8,2000))
assert np.isclose(clustered_se(x,np.arange(len(x))),naive_se(x))
assert np.isclose(paired_se(x,x),0)There is a deliberate difference between plug-in binomial standard error and naive_se: the latter uses sample variance with divisor . They approach one another for large . The former gives the exercise value; do not confuse its divisor with that of the generic function.
Coverage by simulation
Each repetition generates 40 independent documents, ten questions each, and population accuracy 0.8. For each document it chooses whether all answers are one common Bernoulli or ten independent Bernoulli draws. Mixture parameter controls correlation. Each normal interval is checked for the known population value; the repetition unit is a benchmark, not a question. Also compare Wilson coverage with genuinely independent data. A simulated rate does not prove coverage for every population.
import numpy as np
from scipy.stats import norm
rng=np.random.default_rng(7123)
reps,G,m,p=2000,40,10,.8
for rho in (0., .3, .7):
shared=rng.random((reps,G,1)) < rho
common=rng.random((reps,G,1)) < p
independent=rng.random((reps,G,m)) < p
x=np.where(shared,common,independent).astype(float)
means=x.mean(axis=(1,2))
se_naive=x.reshape(reps,-1).std(axis=1,ddof=1)/np.sqrt(G*m)
sums=(x-means[:,None,None]).sum(axis=2)
se_group=np.sqrt(G/(G-1)*np.sum(sums*sums,axis=1))/(G*m)
naive=np.mean(np.abs(means-p)<=norm.ppf(.975)*se_naive)
grouped=np.mean(np.abs(means-p)<=norm.ppf(.975)*se_group)
print('rho',rho,'ingenuo',round(naive,4),'agrupado',round(grouped,4))
k=rng.binomial(100,.8,size=reps)
coverage=np.mean([wilson_interval(int(v),100)[0] <= .8 <= wilson_interval(int(v),100)[1] for v in k])
print('Wilson independiente:',round(coverage,4))The figure simulation uses another deterministic sequence and 500 repetitions, so it need not match this cell’s 2000 exactly. Clustered coverage below 95% in a finite sample does not mean grouping is irrelevant. Repeat with more documents and examine Monte Carlo bias and dispersion. If questions are selected by convenience or filtered after seeing results, no bar fixes selection bias.
Exercises
def clustered_se(scores, cluster_ids):
pass