Reading history

Comparing Machine Learning Models with Statistical Tests

7 min read 0 views

Learn to compare machine learning models fairly with McNemar's test and the corrected t-test for cross-validation scores in Python.

Model A scores 96.5% and model B scores 94.3%. Is A really better, or did it just get luckier test rows? A different random split might flip the result. In this lesson you will use two statistical tests to answer that question: McNemar’s test for a single test set, and a corrected t-test for cross-validation scores.

In this lesson you will learn

  • Why a small gap in accuracy can be pure chance
  • What a p-value tells you when comparing models
  • How McNemar’s test uses only the rows where models disagree
  • Why the usual t-test on cross-validation scores is too confident
  • How the Nadeau and Bengio correction fixes it

You should know cross-validation and cross-validation strategies.

Luck or Real Skill?

Think of two cricket batsmen. One scores 45 runs and the other 40 in a single match. That one match does not prove the first is better. Over 20 matches, a steady gap would be more convincing.

Model scores work the same way. The test set is a sample, and a different sample would give slightly different scores. A statistical test asks: if the two models were truly equal, how likely is a gap this big by chance? That chance is the p-value. A common rule is to call a difference real only when p is below 0.05.

McNemar’s Test on One Test Set

When both models predict the same test rows, many rows are easy and both get them right. Those rows say nothing about which model is better. McNemar’s test looks only at the rows where the models disagree.

import numpy as np
from scipy.stats import binomtest
from sklearn.datasets import load_breast_cancer
from sklearn.model_selection import train_test_split
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.linear_model import LogisticRegression
from sklearn.ensemble import RandomForestClassifier

X, y = load_breast_cancer(return_X_y=True)
X_tr, X_te, y_tr, y_te = train_test_split(X, y, test_size=0.4, random_state=0, stratify=y)

a = make_pipeline(StandardScaler(), LogisticRegression()).fit(X_tr, y_tr)
b = RandomForestClassifier(random_state=0).fit(X_tr, y_tr)
ok_a = a.predict(X_te) == y_te
ok_b = b.predict(X_te) == y_te
print(f"logistic regression accuracy {ok_a.mean():.3f}")
print(f"random forest accuracy       {ok_b.mean():.3f}")

# McNemar's test only looks at the rows where the two models DISAGREE
only_a = int(np.sum(ok_a & ~ok_b))     # A right, B wrong
only_b = int(np.sum(~ok_a & ok_b))     # B right, A wrong
print(f"both right {np.sum(ok_a & ok_b)}, both wrong {np.sum(~ok_a & ~ok_b)}")
print(f"only logistic right {only_a}, only forest right {only_b}")

# If the models were equally good, each disagreement is a coin flip
p = binomtest(only_a, only_a + only_b, 0.5).pvalue
print(f"McNemar exact p-value: {p:.3f}")

Output

logistic regression accuracy 0.965
random forest accuracy       0.943
both right 210, both wrong 3
only logistic right 10, only forest right 5
McNemar exact p-value: 0.302
Random forestrightwrongLogistic regressionrightwrong210both right10only logistic right5only forest right3both wrongMcNemar uses only the orange cells: 10 vs 5
  • Out of 228 test rows, the models agree on 213. Only 15 rows decide the contest.
  • Logistic regression wins 10 of those and the forest wins 5. If the models were equal, each disagreement would be a coin flip.
  • Getting 10 or more heads (or 10 or more tails) in 15 flips happens about 30% of the time. So p = 0.302, which is well above 0.05.
  • Conclusion: the 2-point gap could easily be luck. We have no strong evidence that one model is better.

We used binomtest from SciPy, which gives the exact version of McNemar’s test. It works well even when there are few disagreements.

Testing Cross-Validation Scores

Cross-validation gives many scores per model. Repeated 10-fold cross-validation with 5 repeats gives 50. Since both models use the same folds, we can subtract their scores fold by fold and test whether the average gap is above zero.

import numpy as np
from scipy.stats import t as t_dist
from sklearn.datasets import load_breast_cancer
from sklearn.model_selection import RepeatedStratifiedKFold, cross_val_score
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.linear_model import LogisticRegression
from sklearn.ensemble import RandomForestClassifier

X, y = load_breast_cancer(return_X_y=True)
cv = RepeatedStratifiedKFold(n_splits=10, n_repeats=5, random_state=0)   # 50 scores each

a = cross_val_score(make_pipeline(StandardScaler(), LogisticRegression()), X, y, cv=cv)
b = cross_val_score(RandomForestClassifier(random_state=0), X, y, cv=cv)
d = a - b                                   # same folds, so we can pair the scores
k = len(d)
print(f"logistic {a.mean():.4f}   forest {b.mean():.4f}   mean gap {d.mean():.4f}")

# Naive paired t-test: pretends the 50 scores are independent (they are not)
t_naive = d.mean() / (d.std(ddof=1) / np.sqrt(k))
p_naive = 2 * t_dist.sf(abs(t_naive), k - 1)

# Corrected t-test (Nadeau and Bengio): training sets overlap, so widen the variance
test_over_train = 1 / 9                     # 10-fold: test part / train part
t_corr = d.mean() / np.sqrt((1 / k + test_over_train) * d.var(ddof=1))
p_corr = 2 * t_dist.sf(abs(t_corr), k - 1)

print(f"naive t-test     p = {p_naive:.4f}")
print(f"corrected t-test p = {p_corr:.4f}")

Output

logistic 0.9789   forest 0.9638   mean gap 0.0151
naive t-test     p = 0.0000
corrected t-test p = 0.0654
  • The naive paired t-test says p = 0.0000, which looks like a certain win.
  • But the 50 scores are not independent. Each training set shares about 89% of its rows with the others, so the scores move together. The naive test counts the same evidence many times.
  • The corrected test, from Nadeau and Bengio (2003), adds the term test_over_train to the variance. This makes the test honest about the overlap. Now p = 0.065.
  • That is close to 0.05 but not below it. Logistic regression is probably a little better, but the evidence is not strong.

More folds do not mean more proof

With the naive test, adding more repeats always shrinks the p-value, even if the models are equal. You could “prove” anything by running more folds. The corrected test does not have this problem, because its variance never shrinks below the overlap term.

Which Test Should I Use?

SituationTest
One fixed test set, both models predict itMcNemar’s test
K-fold or repeated cross-validationCorrected paired t-test
Many models on many datasetsFriedman test with a post-hoc test

A significant result only says the gap is probably real. It does not say the gap is big enough to matter. A 0.1% gain may be real but not worth a model that is ten times slower.

Common Mistakes

  1. Picking the winner by the bigger number alone. Always ask whether the gap is larger than the noise.
  2. Using an unpaired test. Both models saw the same rows, so compare them row by row or fold by fold.
  3. Running the naive t-test on cross-validation scores. It is far too confident, as the output shows.
  4. Testing many models and reporting the best p-value. With 20 comparisons, one will look “significant” by chance.

Practice Exercises

Exercise 1. Two models disagree on 40 test rows. Model A is right on 30 of them and model B on 10. Would McNemar’s test likely find a real difference?

Show answer

Yes. Getting 30 or more heads in 40 fair coin flips is very rare (p is about 0.002). So A is very likely better, not just lucky.

Exercise 2. In cmp2.py, what is test_over_train for 5-fold cross-validation?

Show answer

In 5-fold cross-validation, each test part is 1/5 of the data and the training part is 4/5. So test_over_train = (1/5) / (4/5) = 1/4 = 0.25.

Frequently Asked Questions

What does a p-value of 0.05 mean when comparing models?

It means that if the two models were truly equal, a gap at least this large would appear about 5% of the time by chance. A smaller p-value is stronger evidence that the gap is real.

Why not just use a bigger test set?

A bigger test set does make results more reliable, and you should use one when you can. Statistical tests still help you judge how reliable your result is with the data you have.

Does a high p-value mean the models are equal?

No. It only means the data does not show a clear difference. The models might differ by a small amount that the test is too weak to detect.

Summary

  • A gap in scores can be luck; a statistical test measures how likely that is.
  • McNemar’s test uses only the rows where two models disagree.
  • The naive t-test on cross-validation scores is far too confident.
  • Use the Nadeau and Bengio corrected t-test for cross-validation results.

Next: Data Drift and Model Monitoring in Python.

Lessons are also marked complete when you click Next.

Leave a Reply

Your email address will not be published. Required fields are marked *