Module contents
Lesson 11 of 23Review 70 min

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.

InteractiveThe same table, three conventions
ABAccuracy (common scale)

Overlap of marginal error bars does not replace the paired difference interval: correlation between seeds matters. The plot uses the same results under each convention.

10
A ± margin0.803 ± 0.012
B ± margin0.808 ± 0.012
Paired normal CI for B−A0.003 to 0.008
Change seed count and convention. The series are a paired synthetic mathematical example, not real model results. Compare individual bars with the difference interval.

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 XiX_i. Since Var⁡(Xi)=p(1−p)\Var(X_i)=p(1-p) and independence eliminates covariances, Var⁡(p^)=p(1−p)/n\Var(\hat p)=p(1-p)/n. The plug-in estimated standard error is p^(1−p^)/n\sqrt{\hat p(1-\hat p)/n}. 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 p^±zp^(1−p^)/n\hat p\pm z\sqrt{\hat p(1-\hat p)/n} can perform poorly near 0 or 1 and even leave the probability range. Inverting the score test yields the Wilson interval. With z=Φ−1(1−α/2)z=\Phi^{-1}(1-\alpha/2), its endpoints are

p^+z2/(2n)±zp^(1−p^)/n+z2/(4n2)1+z2/n.\frac{\hat p+z^2/(2n)\pm z\sqrt{\hat p(1-\hat p)/n+z^2/(4n^2)}}{1+z^2/n}.

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 pp. 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 GG be the number of documents, NN the total number of questions, xˉ=N−1∑g,ixgi\bar x=N^{-1}\sum_{g,i}x_{gi} and Sg=∑i(xgi−xˉ)S_g=\sum_i(x_{gi}-\bar x). A sandwich estimator for the question-weighted mean, with finite-group correction, is

SE⁡^grupo=1NGG−1∑g=1GSg2.\widehat{\operatorname{SE}}_{\rm grupo}=\frac{1}{N}\sqrt{\frac{G}{G-1}\sum_{g=1}^{G}S_g^2}.

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 N\sqrt N. 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 mm and common intragroup correlation ρ\rho, mean variance is multiplied relative to independence by 1+(m−1)ρ1+(m-1)\rho. This is the design effect. It follows from counting mm variances and m(m−1)m(m-1) 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.

InteractiveCoverage when questions are grouped
NaiveClusteredLine: 95%

Each document shares a difficulty variable in a proportion of cases; documents are independent. Cluster correction can still cover less than nominal with few groups.

40
0.3
Naive coverage64.2 %
Clustered coverage90.4 %
Each document contains ten questions. Adjust correlation and compare simulated coverage of naive and clustered normal intervals; the line marks 95%. Each result comes from the generation model described in the lab, not a real benchmark.

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 ρ\rho, its intragroup correlation is precisely ρ\rho. 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 pp, with nn items per model, a two-sided test at level α\alpha, and approximate power 1−β1-\beta, we obtain

MDD⁡≈(z1−α/2+z1−β)2p(1−p)(1−ρ)n.\operatorname{MDD}\approx(z_{1-\alpha/2}+z_{1-\beta})\sqrt{\frac{2p(1-p)(1-\rho)}{n}}.

Here ρ\rho 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 nn if other assumptions hold.

Pairing’s reduction appears by expanding variance of Di=XBi−XAiD_i=X_{Bi}-X_{Ai}. If both marginals have variance p(1−p)p(1-p) and correlation ρ\rho, then Var⁡(Di)=2p(1−p)−2ρp(1−p)\Var(D_i)=2p(1-p)-2\rho p(1-p). For nn independent pairs, mean variance is that quantity divided by nn. 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 p=0.8p=0.8, n=2000n=2000, α=0.05\alpha=0.05, 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.

InteractiveTest size and detectable difference
0.00.10.2Independent blue · paired orangeItems: 100 to 10,000MDD

The dashed line indicates the chosen size. The curve is a local approximation, not a guarantee for every sample.

0.80
0.30
2000
Approximate paired MDD2.96 points
Approximate independent MDD3.54 points
Change accuracy, correlation, size, and power. Curves calculate the explicit normal approximation in the text, with two-sided α 0.05; they are not observed data.

What the ± sign communicates

The error-bar convention must name the quantity, number and type of units, and procedure. With RR independent seeds and sample deviation ss, ss describes dispersion of individual results, while s/Rs/\sqrt R estimates standard error of their mean. A t interval for the mean is xˉ±tR−1,1−α/2s/R\bar x\pm t_{R-1,1-\alpha/2}s/\sqrt R 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.

[ ]Standard errors, Wilson, and approximate powerBrowser
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 n−1n-1. They approach one another for large nn. 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 ρ\rho 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.

[ ]Naive, clustered, and Wilson coverageBrowser
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

Numeric
A model answers 820 of 1000 independent items correctly. Calculate the plug-in binomial standard error of accuracy on a 0 to 1 scale.
Numeric
With base accuracy 0.8, 2000 independent items per model, two-sided α 0.05, and power 0.8, calculate approximate MDD on a 0 to 1 scale.
Code
Implement clustered_se(scores, cluster_ids) for the item-weighted mean. Use the G/(G−1) correction; reject incompatible inputs or fewer than two groups.
def clustered_se(scores, cluster_ids):
  pass
Shift+Enter to run
Quiz
A table says 85.1 ± 0.3 and 85.6 ± 0.4, with no further information. What conclusion is justified?
Quiz
A benchmark has several questions per document. You want the per-question mean on new documents. What do you resample?
Key idea
A bar has meaning only after defining the estimand, repeated unit, and sources of variation. Test size, pairing, and clustering determine how much difference you can distinguish.