A Comparison Bench with Honest Cross-Validation
"Model B beats model A by 1.5 points" is one of the most frequently wrong sentences in machine learning. The gap may be noise from one lucky split, it may come from tuning B on the very data it was scored on, or from preprocessing fitted on the test folds. This lesson builds a small bench that compares the course's classifiers on three built-in data sets with the same splits for every model, then answers two questions properly: is a difference real, and how good is a tuned model really?
Rules of the bench
- Same splits for every model. Pass one splitter object (with a fixed
random_state) to everycross_val_scorecall, so models are compared on identical train/test partitions and differences are paired. - Preprocessing inside the pipeline. Scalers, imputers, encoders and PCA are refitted on each training fold.
- Report the spread, not just the mean; with 5 folds of 150 rows, one fold's accuracy moves in steps of 1/30.
- Include baselines: a majority-class
DummyClassifierand a simple linear model. - Tuning happens inside the training folds (nested cross-validation), never on the folds used for scoring.
- The test set is used once, after all choices are made, if you have one at all.
The bench
Seven classifiers, three data sets (iris: 150 flowers, 3 classes; wine: 178 wines, 3 classes; breast cancer: 569 tumours, 2 classes), 5-fold stratified cross-validation, default hyperparameters:
import numpy as np
from sklearn.datasets import load_breast_cancer, load_wine, load_iris
from sklearn.model_selection import StratifiedKFold, cross_val_score
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.dummy import DummyClassifier
from sklearn.linear_model import LogisticRegression
from sklearn.neighbors import KNeighborsClassifier
from sklearn.svm import SVC
from sklearn.naive_bayes import GaussianNB
from sklearn.ensemble import RandomForestClassifier, HistGradientBoostingClassifier
datasets = {"iris": load_iris, "wine": load_wine, "cancer": load_breast_cancer}
models = {
"majority class": DummyClassifier(),
"logistic": make_pipeline(StandardScaler(), LogisticRegression(max_iter=2000)),
"kNN": make_pipeline(StandardScaler(), KNeighborsClassifier()),
"SVM (RBF)": make_pipeline(StandardScaler(), SVC()),
"naive Bayes": GaussianNB(),
"random forest": RandomForestClassifier(n_estimators=100, random_state=0, n_jobs=1),
"hist. boosting": HistGradientBoostingClassifier(max_iter=50, random_state=0),
}
cv = StratifiedKFold(n_splits=5, shuffle=True, random_state=0) # the same 5 splits for every model
print(f"{'':15s}" + "".join(f"{d:>14s}" for d in datasets))
for mname, model in models.items():
row = []
for dname, load in datasets.items():
X, y = load(return_X_y=True)
s = cross_val_score(model, X, y, cv=cv)
row.append(f"{s.mean():.3f}+/-{s.std():.3f}")
print(f"{mname:15s}" + "".join(f"{r:>14s}" for r in row)) iris wine cancer
majority class 0.333+/-0.000 0.399+/-0.015 0.627+/-0.004
logistic 0.960+/-0.013 0.983+/-0.014 0.979+/-0.014
kNN 0.953+/-0.034 0.961+/-0.013 0.965+/-0.021
SVM (RBF) 0.953+/-0.016 0.983+/-0.014 0.977+/-0.007
naive Bayes 0.960+/-0.013 0.972+/-0.000 0.939+/-0.020
random forest 0.940+/-0.025 0.972+/-0.018 0.965+/-0.015
hist. boosting 0.940+/-0.025 0.972+/-0.018 0.975+/-0.010
What the table supports, and what it does not:
- Every model beats the baseline by a wide margin, so all of them learn something. The baseline also shows the class balance (0.627 on cancer: 62.7 % benign).
- On these small, clean data sets the linear model is among the best everywhere (0.960, 0.983, 0.979). The tree ensembles, which shine on large tabular data, do not lead here.
- Most gaps are smaller than the spreads. On iris, the difference between 0.960 and 0.940 is three flowers out of 150. Ranking the models on this table alone would be ranking noise.
- Naive Bayes is clearly weaker on cancer (0.939), where its 30 features are strongly correlated (why).
A regression bench works the same way with KFold and a regression metric; the mini project runs one.
Is a difference real? Paired comparison
On the cancer data, logistic regression leads the random forest by about 1.5 points. Repeating 5-fold cross-validation 4 times with different shuffles gives 20 paired scores. A plain paired t-test treats the 20 differences as independent, but they are not: the training sets overlap heavily, so the differences are correlated and the plain test is far too confident. The Nadeau-Bengio corrected t-test inflates the variance by a term for that overlap:
with the number of splits and the sample variance of the differences (Model Selection and Cross-Validation).
import numpy as np
from scipy import stats
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=5, n_repeats=4, random_state=0) # 20 splits, shared by both models
a = cross_val_score(make_pipeline(StandardScaler(), LogisticRegression(max_iter=2000)), X, y, cv=cv)
b = cross_val_score(RandomForestClassifier(n_estimators=100, random_state=0, n_jobs=1), X, y, cv=cv)
d = a - b # paired: same split, two models
print(f"logistic {a.mean():.4f} forest {b.mean():.4f} mean difference {d.mean():+.4f}")
print("splits won by logistic / forest / tied:", int((d > 0).sum()), int((d < 0).sum()), int((d == 0).sum()))
k, n_test, n_train = 20, len(y) / 5, len(y) * 4 / 5
naive_t = d.mean() / (d.std(ddof=1) / np.sqrt(k))
corr_t = d.mean() / np.sqrt((1 / k + n_test / n_train) * d.var(ddof=1)) # Nadeau-Bengio correction
print(f"naive paired t = {naive_t:.2f}, p = {2 * stats.t.sf(abs(naive_t), k - 1):.4f}")
print(f"corrected t = {corr_t:.2f}, p = {2 * stats.t.sf(abs(corr_t), k - 1):.4f}")logistic 0.9754 forest 0.9600 mean difference +0.0154
splits won by logistic / forest / tied: 16 2 2
naive paired t = 4.57, p = 0.0002
corrected t = 1.87, p = 0.0776
Logistic regression wins 16 of the 20 splits, and the naive test calls the difference overwhelming (). The corrected test, which accounts for the shared training data, gives : suggestive, not conclusive. The honest summary: "logistic regression is at least as good as the forest on this data, probably slightly better; prefer it, since it is also simpler". A -value is not the whole story either: a difference of 1.5 points may or may not matter for the application.
How good is the tuned model? Nested cross-validation
When you tune hyperparameters with GridSearchCV, its best_score_ is the best of many scores on the same folds, so it is biased upwards: some of the "best" is luck. Nested cross-validation puts the whole search inside an outer loop, so each outer test fold is never seen by the tuning. Since generated data can produce as many fresh rows as we like, the example can check both estimates against the true accuracy, for five different data sets of 150 rows:
import numpy as np
from sklearn.datasets import make_classification
from sklearn.model_selection import GridSearchCV, StratifiedKFold, cross_val_score
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.svm import SVC
grid = {"svc__C": [0.1, 1, 10, 100], "svc__gamma": [0.001, 0.01, 0.1, 1]}
pipe = make_pipeline(StandardScaler(), SVC())
inner = StratifiedKFold(3, shuffle=True, random_state=0)
outer = StratifiedKFold(5, shuffle=True, random_state=1)
print("data set best inner-CV score nested CV true accuracy (5000 fresh rows)")
rows = []
for seed in range(3, 8):
# 150 rows to learn from, plus 5000 fresh rows from the same source to check the estimates against
X_all, y_all = make_classification(n_samples=5150, n_features=20, n_informative=4, flip_y=0.1, random_state=seed)
X, y, X_new, y_new = X_all[:150], y_all[:150], X_all[150:], y_all[150:]
search = GridSearchCV(pipe, grid, cv=inner).fit(X, y) # tuned and scored on the same folds
nested = cross_val_score(GridSearchCV(pipe, grid, cv=inner), X, y, cv=outer).mean() # tuned inside each outer fold
true = search.score(X_new, y_new)
rows.append((search.best_score_, nested, true))
print(f"{seed:8d} {search.best_score_:19.3f} {nested:9.3f} {true:9.3f}")
m = np.mean(rows, axis=0)
print(f"{'mean':>8s} {m[0]:19.3f} {m[1]:9.3f} {m[2]:9.3f}")data set best inner-CV score nested CV true accuracy (5000 fresh rows)
3 0.700 0.633 0.742
4 0.787 0.780 0.775
5 0.727 0.700 0.730
6 0.733 0.720 0.686
7 0.827 0.820 0.753
mean 0.755 0.731 0.737
On every one of the five data sets the grid search's own best score is above the nested estimate, and on average it overstates the true accuracy (0.755 against 0.737), while the nested estimate is close to it on average (0.731). Individual estimates still miss by several points in either direction: with 150 rows, any estimate is noisy. With 16 hyperparameter combinations the optimism is modest; with hundreds (or with many models compared on the same folds) it grows. Nested CV is the estimate to report; the inner search's best score is only for choosing the hyperparameters.
Pitfalls
- Different splits for different models. Then part of each difference is the splits, not the models.
- Selecting the best of many models and reporting its CV score. Model choice is tuning too; the winner's score is optimistic.
- Treating fold scores as independent. Use the corrected test or simply report the spread and be modest.
- Fitting anything on all the data before cross-validation: scalers, feature selection, target encoding. Data Preparation covers leakage and how much it inflates scores.
Practice
- Five folds give accuracies 0.95, 0.97, 0.96, 0.93 and 0.99 for model A and 0.94, 0.97, 0.95, 0.93, 0.98 for B, on the same folds. Compute the paired differences and their mean. Is B ever better?
Answer
Differences A minus B: 0.01, 0, 0.01, 0, 0.01; mean 0.006. B never wins and ties twice. The differences are consistent, but with five overlapping folds and gaps of one or two examples, the corrected test would still be cautious.
- You tried 40 hyperparameter settings and report
best_score_ = 0.91. A colleague asks for an unbiased estimate. What do you run?
Answer
Nested cross-validation: cross_val_score(GridSearchCV(model, grid, cv=inner), X, y, cv=outer), or a final evaluation on a test set that played no part in the search.
Test yourself
Why pass the same cv splitter object to every model on the bench?
- It is faster
- So every model is trained and tested on identical splits and differences are paired
- Because scikit-learn requires it
- To use more data
Why is the naive paired t-test over cross-validation folds too optimistic?
- It uses too few folds
- The fold scores are correlated because the training sets overlap
- It ignores the mean
- It needs normal data
What does nested cross-validation estimate?
- The best hyperparameters
- The performance of the whole procedure, tuning included, on unseen data
- The training error
- The variance of the data