Simple Algorithm
Machine Learning · Convergence · 26 min

Comparing Models Statistically

Paired tests, McNemar and honest benchmark comparisons.

Model B beats model A by 1.2 points of accuracy. A real improvement, a lucky test set, or a lucky random seed? This lesson separates the sources of variation in a measured score, puts an honest interval on a single accuracy, compares two models with paired tests on one test set and across retrainings, handles many datasets and many comparisons at once, and ends with Bayesian alternatives and what honest benchmarking still struggles with.

What you’ll learn

  • Put a confidence interval on a test accuracy, and explain why the Wilson interval beats the textbook Wald interval.
  • Derive McNemar's test from the discordant pairs, and quantify how much power pairing buys.
  • Explain why resampled tt-tests are anticonservative, derive the Nadeau–Bengio correction, and apply Dietterich's 5×2cv test.
  • Compare classifiers over many datasets with the Wilcoxon signed-rank, Friedman and Nemenyi tests, and prove that Holm's procedure controls the family-wise error rate.
  • Read a Bayesian comparison with a region of practical equivalence, and design experiments that account for seeds and data splits.

Which variation, and an interval for one accuracy

A measured score moves for several reasons: which examples landed in the test set, which ones were used for training, the algorithm's internal randomness (initialization, data order, dropout), and the hyperparameter search. Which of these a comparison must include depends on the question (Dietterich, 1998):

  • Is this trained model better than that one, on the population the test set was drawn from? Only the test sample varies.
  • Is algorithm A better than algorithm B for training sets of this size from this population? Training samples and seeds vary too, so the models must be retrained.

Start with the first question and a single model. If the nn test examples are i.i.d. and the model is fixed, the number it classifies correctly is k∼Binomial(n,p)k\sim\mathrm{Binomial}(n,p), where pp is its true accuracy.

DerivationThe Wilson score interval (1927)
  1. ∣p^−p∣ ≤ zp(1−p)n⟺(p^−p)2≤z2n p(1−p)\abs{\hat p-p}\ \le\ z\sqrt{\frac{p(1-p)}{n}}\quad\Longleftrightarrow\quad(\hat p-p)^2\le\frac{z^2}{n}\,p(1-p)

    The textbook (Wald) confidence interval p^±zp^(1−p^)/n\hat p\pm z\sqrt{\hat p(1-\hat p)/n} plugs the estimate into the standard error. Its coverage is erratic, and can be poor even for large nn (Brown, Cai & DasGupta, 2001). Instead, keep every pp that a level-α\alpha test, using the standard error under that pp, would not reject:

  2. p∈p^+z22n1+z2n ± z1+z2np^(1−p^)n+z24n2p\in\frac{\hat p+\frac{z^2}{2n}}{1+\frac{z^2}{n}}\ \pm\ \frac{z}{1+\frac{z^2}{n}}\sqrt{\frac{\hat p(1-\hat p)}{n}+\frac{z^2}{4n^2}}

    This is a quadratic inequality in pp. Its solution is an interval whose center is pulled from p^\hat p toward 12\tfrac12:

  3. p^=1:p ≥ 11+z2/n=11+3.84/50=0.929\hat p=1:\qquad p\ \ge\ \frac{1}{1+z^2/n}=\frac{1}{1+3.84/50}=0.929

    At the edge the difference is stark. A model that gets all 50 test examples right has a Wald interval of width zero, [1,1][1,1]; the Wilson interval at 95% is [0.929,1][0.929,1], since its lower end is 1/(1+z2/n)1/(1+z^2/n). With 45 of 50 correct, Wald gives [0.817,0.983][0.817,0.983] and Wilson [0.786,0.957][0.786,0.957], which never pokes above 1.

Predict before you look

A model classifies 900 of 1,000 test examples correctly. How wide is the 95% confidence interval for its accuracy, in percentage points (upper end minus lower end)?

Show the answer

3.7 points

2×1.960.9×0.1/1000≈3.72\times1.96\sqrt{0.9\times0.1/1000}\approx3.7 points; Wilson gives [88.0%,91.7%][88.0\%,91.7\%], the same width. So two models scored separately on test sets of 1,000 cannot be told apart at the 1-point level. Scoring them on the same examples does much better, as the next step shows.

Two models, one test set: pair the comparison

Two models evaluated on the same examples make correlated errors: hard examples trip both. Sort the test examples into four groups: both right, both wrong, bb where only A is right, and cc where only B is right. The difference in accuracy is (b−c)/n(b-c)/n, so the examples on which the models agree carry no information about which is better.

In simulations by Dietterich (1998), McNemar's test had acceptable Type I error and was the test to use when a learning algorithm can be run only once. Its limit is built in: it treats the two trained models as fixed, so it answers the first question of the previous step, not the second. A different training sample or seed might reverse the result, and McNemar's test cannot see that.

Check your understanding

In McNemar's test for two classifiers on one test set, which test examples affect the statistic?

  1. All of them, weighted equally
  2. Only those both models get wrong
  3. Only those on which exactly one of the two models is correct
  4. Only those both models get right
Show the answer

C. Only those on which exactly one of the two models is correct

The statistic uses bb and cc alone. Examples both models get right or both get wrong shift the two accuracies equally and say nothing about which model is better; conditioning on them removes their noise, which is where pairing gets its power.

Retraining: correlated folds and corrected tests

To compare algorithms, retrain them on many training sets, for example over the folds of KK-fold cross-validation or over JJ random train/test splits, and record the paired differences d1,…,dJd_1,\dots,d_J in test score. The naive paired tt-test uses t=dˉ/(S/J)t=\bar d/(S/\sqrt J) with the sample standard deviation SS. But the training sets overlap heavily, and with random splits the test sets overlap too, so the djd_j are positively correlated, S2/JS^2/J underestimates Var⁡(dˉ)\Var(\bar d), and the test rejects a true null far too often (Dietterich, 1998). Worse, no estimator of the variance of KK-fold cross-validation is unbiased under all distributions (Bengio & Grandvalet, 2004).

DerivationThe Nadeau–Bengio correction (2003)
  1. Var⁡(dˉ)=σ2J(1+(J−1)ρ)=σ2[ρ+1−ρJ]\Var(\bar d)=\frac{\sigma^2}{J}\big(1+(J-1)\rho\big)=\sigma^2\Big[\rho+\frac{1-\rho}{J}\Big]

    Model the JJ differences as equicorrelated, each with variance σ2\sigma^2 and pairwise correlation ρ\rho. The variance of their mean does not shrink to zero as JJ grows:

  2. E[S2]=1J−1 E∑j=1J(dj−dˉ)2=σ2(1−ρ)⟹Var⁡(dˉ)=E[S2](1J+ρ1−ρ)\E\big[S^2\big]=\frac{1}{J-1}\,\E\sum_{j=1}^J(d_j-\bar d)^2=\sigma^2(1-\rho)\quad\Longrightarrow\quad\Var(\bar d)=\E\big[S^2\big]\Big(\frac1J+\frac{\rho}{1-\rho}\Big)

    The sample variance only sees the spread of the djd_j around their shared component, so it estimates σ2(1−ρ)\sigma^2(1-\rho), not σ2\sigma^2:

  3. t=dˉ(1J+ntestntrain)S2t=\frac{\bar d}{\sqrt{\Big(\dfrac1J+\dfrac{n_{\text{test}}}{n_{\text{train}}}\Big)S^2}}

    The correlation cannot be estimated from the djd_j themselves. Nadeau & Bengio's heuristic ρ≈ntest/(ntrain+ntest)\rho\approx n_{\text{test}}/(n_{\text{train}}+n_{\text{test}}) gives ρ/(1−ρ)=ntest/ntrain\rho/(1-\rho)=n_{\text{test}}/n_{\text{train}}, and the corrected resampled tt-test, compared with a tt distribution on J−1J-1 degrees of freedom:

5×2cv. Dietterich proposed five replications of 2-fold cross-validation. In replication ii, let pi(1),pi(2)p_i^{(1)},p_i^{(2)} be the differences on the two folds, pˉi\bar p_i their mean and si2=(pi(1)−pˉi)2+(pi(2)−pˉi)2s_i^2=(p_i^{(1)}-\bar p_i)^2+(p_i^{(2)}-\bar p_i)^2. Under the null, t~=p1(1)/15∑i=15si2\tilde t=p_1^{(1)}\big/\sqrt{\tfrac15\sum_{i=1}^5s_i^2} is approximately t5t_5. With half the data in each training set the folds are less entangled, and Alpaydın (1999) improved the test into a 5×2cv FF test that uses all ten differences, with lower Type I error and higher power.

Many datasets, many comparisons

Papers usually compare several methods on a suite of NN datasets. Demšar (2006) reviewed the practice and recommended nonparametric tests. Averaging accuracies across datasets is questionable because errors on different problems are not commensurable; a paired tt-test across datasets adds assumptions of normality and sensitivity to outliers; counting wins (the sign test) is valid but weak.

Two classifiers: the Wilcoxon signed-rank test (Wilcoxon, 1945). Rank the absolute differences ∣di∣\abs{d_i} over the datasets, let R+R^+ and R−R^- be the sums of the ranks of the positive and the negative differences, and use T=min⁡(R+,R−)T=\min(R^+,R^-), with exact tables for small NN and for larger NN the normal approximation z=(T−N(N+1)4)/N(N+1)(2N+1)/24z=\big(T-\tfrac{N(N+1)}4\big)\big/\sqrt{N(N+1)(2N+1)/24}. It uses the size of each difference through its rank, which makes it more powerful than counting wins and robust to one dataset with a huge difference.

kk classifiers: the Friedman test (Friedman, 1937). Rank the classifiers within each dataset (1 = best) and average to get R1,…,RkR_1,\dots,R_k. Under the null that all are equivalent, χF2\chi^2_F below is approximately χk−12\chi^2_{k-1}; Iman & Davenport (1980) showed it is conservative and proposed FFF_F, approximately FF-distributed with k−1k-1 and (k−1)(N−1)(k-1)(N-1) degrees of freedom:

χF2=12Nk(k+1)[∑jRj2−k(k+1)24],FF=(N−1) χF2N(k−1)−χF2.\chi^2_F=\frac{12N}{k(k+1)}\Big[\sum_jR_j^2-\frac{k(k+1)^2}{4}\Big],\qquad F_F=\frac{(N-1)\,\chi^2_F}{N(k-1)-\chi^2_F}.

If it rejects, the Nemenyi post-hoc test declares two classifiers different when their average ranks differ by more than the critical difference CD=qαk(k+1)/(6N)\mathrm{CD}=q_\alpha\sqrt{k(k+1)/(6N)}, where qαq_\alpha is a Studentized-range quantile divided by 2\sqrt2 (q0.05=2.569q_{0.05}=2.569 for k=4k=4, 2.7282.728 for k=5k=5).

Predict before you look

Four classifiers are compared on N=20N=20 datasets. What is the Nemenyi critical difference in average rank at α=0.05\alpha=0.05?

Show the answer

1.05

CD=2.5694⋅5/(6⋅20)=2.5691/6≈1.05\mathrm{CD}=2.569\sqrt{4\cdot5/(6\cdot20)}=2.569\sqrt{1/6}\approx1.05. With ranks running from 1 to 4, two classifiers must be about a full rank apart on average to be declared different: twenty datasets is not a lot.

Multiple comparisons. Running mm tests at level α\alpha makes a false rejection likely: with 10 independent true nulls at 5%, the chance of at least one is 1−0.9510=0.401-0.95^{10}=0.40. The family-wise error rate (FWER) is the probability of any false rejection. Bonferroni tests each hypothesis at α/m\alpha/m, which keeps the FWER at most α\alpha by the union bound, under any dependence. Holm (1979) sorts the pp-values p(1)≤⋯≤p(m)p_{(1)}\le\dots\le p_{(m)} and rejects H(1),H(2),…H_{(1)},H_{(2)},\dots for as long as p(i)≤α/(m−i+1)p_{(i)}\le\alpha/(m-i+1), stopping at the first failure. It also holds the FWER at α\alpha under any dependence, and rejects everything Bonferroni does and often more. When many comparisons are exploratory, controlling the false discovery rate instead (Benjamini & Hochberg, 1995) is a gentler criterion.

DerivationWhy Holm controls the family-wise error rate
  1. P(Ec)≤∑i∈I0P(pi≤αm0)≤m0⋅αm0=αP(E^c)\le\sum_{i\in I_0}P\Big(p_i\le\frac{\alpha}{m_0}\Big)\le m_0\cdot\frac{\alpha}{m_0}=\alpha

    Let I0I_0 be the set of true null hypotheses, m0=∣I0∣≥1m_0=\abs{I_0}\ge1, with valid pp-values: P(pi≤u)≤uP(p_i\le u)\le u for i∈I0i\in I_0. Consider the event EE that every true null has pi>α/m0p_i>\alpha/m_0. By the union bound, whatever the dependence between the pp-values:

  2. p(j)≤αm−j+1≤αm0p_{(j)}\le\frac{\alpha}{m-j+1}\le\frac{\alpha}{m_0}

    Suppose a true null is rejected, and let step jj be the first time this happens. All hypotheses rejected before it are false nulls, so j−1≤m−m0j-1\le m-m_0, i.e. m−j+1≥m0m-j+1\ge m_0. Rejection at step jj needs p≤α/(m−j+1)≤α/m0p\le\alpha/(m-j+1)\le\alpha/m_0:

  3. FWER≤P(Ec)≤α\mathrm{FWER}\le P(E^c)\le\alpha

    That contradicts EE. So a false rejection can only occur outside EE, and the FWER is at most P(Ec)≤αP(E^c)\le\alpha. Bonferroni's thresholds α/m\alpha/m are never larger than Holm's, which is why Holm is uniformly more powerful.

Beyond the p-value

A pp-value answers a narrow question: how surprising the data would be if the null hypothesis were exactly true. It is not the probability that the null is true; with enough data, differences too small to matter become "significant"; and a non-significant result is not evidence that two models are equivalent. Benavoli, Corani, Demšar & Zaffalon (2017) argued that machine learning should move to Bayesian analysis, and gave practical tests.

The Bayesian correlated tt-test models the JJ cross-validation differences as correlated Gaussians with the Nadeau–Bengio ρ\rho. Under a reference ("matching") prior, the posterior of the mean difference μ\mu is a Student tt with J−1J-1 degrees of freedom, location dˉ\bar d and squared scale (1/J+ρ/(1−ρ))S2\big(1/J+\rho/(1-\rho)\big)S^2: numerically the same ingredients as the corrected tt-test, read differently. Declare a region of practical equivalence (rope), say ±1\pm1 point of accuracy, and report three posterior probabilities: A practically better, the two practically equivalent, B practically better.

Key takeaways

  • Decide which variation the comparison must include: test-set sampling only (two trained models), or also training sets and seeds (two learning algorithms).
  • Use the Wilson interval for an accuracy; at n=1000n=1000 and 90% accuracy it is about ±1.9 points. Pairing on the same test examples is far more powerful than comparing two separate intervals.
  • McNemar's test uses only the discordant examples, b∼Binomial(b+c,12)b\sim\mathrm{Binomial}(b+c,\tfrac12) under the null, and speaks about fixed models.
  • Resampled differences are correlated: correct the variance by 1/J+ntest/ntrain1/J+n_{\text{test}}/n_{\text{train}} (Nadeau–Bengio) or use 5×2cv; no estimator of the variance of KK-fold CV is unbiased in general.
  • Across datasets use Wilcoxon or Friedman with post-hoc tests and Holm's correction; Bayesian tests with a region of practical equivalence answer whether a difference is large enough to matter.

Check yourself

In the interactive lesson these are scored with your confidence, and what you miss comes back for review.

Question 1

Two trained classifiers are compared on one test set with McNemar's test, which rejects equality at p=0.001p=0.001. What has been established?

  1. That the first learning algorithm is better than the second for data of this kind
  2. That these two trained models differ in accuracy on the population the test set came from
  3. That retraining either model with a new seed would give the same ranking
  4. That the difference in accuracy is large enough to matter in practice
Show the answer

B. That these two trained models differ in accuracy on the population the test set came from

McNemar's test treats the trained models as fixed and the test examples as the only source of randomness, so it supports a conclusion about these two models. Whether the algorithms differ needs retraining on new samples and seeds, and whether the difference matters is a question of effect size, not of the pp-value.

Question 2

Why does the ordinary paired tt-test on 30 random train/test splits reject a true null hypothesis too often?

  1. Because accuracy differences are never normally distributed
  2. Because 30 splits are too few for the tt distribution
  3. Because overlapping training and test sets make the differences positively correlated, so S2/JS^2/J underestimates the variance of their mean
  4. Because the test should be one-sided
Show the answer

C. Because overlapping training and test sets make the differences positively correlated, so S2/JS^2/J underestimates the variance of their mean

With correlation ρ\rho, Var⁡(dˉ)=σ2[ρ+(1−ρ)/J]\Var(\bar d)=\sigma^2[\rho+(1-\rho)/J], while S2/JS^2/J estimates σ2(1−ρ)/J\sigma^2(1-\rho)/J. The denominator is too small, the tt statistic too large, and the Type I error inflated; more splits make it worse, not better. The Nadeau–Bengio correction adds the missing ntest/ntrainn_{\text{test}}/n_{\text{train}} term.

Question 3

Four comparisons give pp-values 0.001, 0.015, 0.02 and 0.04. At family-wise level α=0.05\alpha=0.05, which hypotheses does Holm's procedure reject?

  1. Only the first
  2. The first two
  3. The first three
  4. All four
Show the answer

D. All four

Holm compares the sorted pp-values with α/4=0.0125\alpha/4=0.0125, α/3≈0.0167\alpha/3\approx0.0167, α/2=0.025\alpha/2=0.025 and α=0.05\alpha=0.05, rejecting until the first failure. Here 0.001≤0.01250.001\le0.0125, 0.015≤0.01670.015\le0.0167, 0.02≤0.0250.02\le0.025 and 0.04≤0.050.04\le0.05, so all four are rejected. Bonferroni, which compares every pp-value with 0.01250.0125, would reject only the first.

Question 4

A model makes no errors on 30 independent test examples. What can you say about its true error rate at 95% confidence?

  1. It is zero
  2. It is below 1%
  3. Nothing, since no errors were observed
  4. It is below roughly 10%
Show the answer

D. It is below roughly 10%

If the error rate were ε\varepsilon, the chance of 30 clean results would be (1−ε)30(1-\varepsilon)^{30}, which falls below 5% once ε>1−0.051/30≈0.095\varepsilon>1-0.05^{1/30}\approx0.095: the "rule of three" upper bound 3/n=0.103/n=0.10. The two-sided Wilson interval gives accuracy at least 0.886. Zero observed errors is compatible with a sizable error rate.

Further reading

  • Q. McNemar, "Note on the sampling error of the difference between correlated proportions or percentages," Psychometrika 12(2), 153–157 (1947).
  • T. G. Dietterich, "Approximate statistical tests for comparing supervised classification learning algorithms," Neural Computation 10(7), 1895–1923 (1998).
  • C. Nadeau & Y. Bengio, "Inference for the generalization error," Machine Learning 52(3), 239–281 (2003).
  • J. Demšar, "Statistical comparisons of classifiers over multiple data sets," Journal of Machine Learning Research 7, 1–30 (2006).
  • A. Benavoli, G. Corani, J. Demšar & M. Zaffalon, "Time for a change: a tutorial for comparing multiple classifiers through Bayesian analysis," Journal of Machine Learning Research 18(77), 1–36 (2017).