Sub topic 13
Comparing models fairly
This chapter assumes you can build a scikit-learn Pipeline, run cross_val_score, and read a ROC AUC value. It also assumes you have already set a baseline and tuned at least one model. Here the question is whether the model that scored highest is actually better, or only luckier or better treated.
What "fair" means
A comparison is fair when the only thing that differs between candidates is the model. Four things must be held constant:
- The data rows used for training and testing.
- The metric.
- The preprocessing procedure, fitted inside each fold.
- The tuning effort each model receives.
If any of these differ, a score gap may come from the setup and not from the model. A random forest evaluated on one split and logistic regression on another can differ by several points from the split alone.
Same folds, same metric
Pass one splitter object to every call. Give it an integer random_state, so each call produces identical splits. With shuffle=True and no seed, every call draws new folds.
Repeating the cross-validation gives more scores per model. RepeatedStratifiedKFold runs the whole k-fold procedure several times with different shuffles. With 5 folds and 3 repeats you get 15 scores per model. This shows how much a score depends on the split.
Also pick one primary metric before you look at results. You can report secondary metrics, but choose the winner on the primary one. Otherwise you can always find a metric where your favorite wins.
A complete comparison
The code below builds the synthetic table from earlier chapters, scores three candidates on identical repeated folds, and compares them fold by fold. It also records fit time, because cost belongs in the comparison.
import numpy as np
import pandas as pd
from sklearn.compose import ColumnTransformer
from sklearn.dummy import DummyClassifier
from sklearn.ensemble import HistGradientBoostingClassifier
from sklearn.impute import SimpleImputer
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import RepeatedStratifiedKFold, cross_validate
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import OneHotEncoder, StandardScaler
rng = np.random.default_rng(0)
n = 500
X = pd.DataFrame({
"age": rng.integers(18, 80, n).astype(float),
"income": rng.normal(50000, 15000, n),
"city": rng.choice(["a", "b", "c"], n),
})
X.loc[rng.choice(n, 25, replace=False), "income"] = np.nan
y = ((X["age"] > 45) ^ (X["city"] == "a")).astype(int)
preprocess = ColumnTransformer([
("num", make_pipeline(SimpleImputer(strategy="median"), StandardScaler()), ["age", "income"]),
("cat", OneHotEncoder(handle_unknown="ignore", sparse_output=False), ["city"]),
])
cv = RepeatedStratifiedKFold(n_splits=5, n_repeats=3, random_state=0)
candidates = {
"baseline": make_pipeline(preprocess, DummyClassifier(strategy="prior")),
"logreg": make_pipeline(preprocess, LogisticRegression(max_iter=1000)),
"hist_gb": make_pipeline(preprocess, HistGradientBoostingClassifier(random_state=0)),
}
scores = {}
for name, model in candidates.items():
res = cross_validate(model, X, y, cv=cv, scoring="roc_auc")
scores[name] = res["test_score"]
print(f"{name:9s} auc {res['test_score'].mean():.3f} "
f"+/- {res['test_score'].std():.3f} "
f"fit {res['fit_time'].mean():.2f}s")
diff = scores["hist_gb"] - scores["logreg"]
k = len(diff)
n_train = n * 4 // 5
n_test = n - n_train
naive_se = diff.std(ddof=1) / np.sqrt(k)
corrected_se = np.sqrt((1 / k + n_test / n_train) * diff.var(ddof=1))
print(f"mean diff {diff.mean():.3f}, naive se {naive_se:.3f}, corrected se {corrected_se:.3f}")Because cv has a fixed seed, every cross_validate call sees the same 15 train/test splits. Score number i for one model therefore pairs with score number i for another. That pairing is what the last block of code uses.
Look at spread, not only the mean
A mean of 0.91 against 0.90 says little until you know how much each score moves between folds. If the standard deviation across folds is 0.02, a 0.01 gap is within noise.
Paired differences are more informative than two separate means. Fold difficulty is shared: a hard fold lowers every model's score. Subtracting the scores fold by fold cancels that shared effect and leaves the model effect.
There is a catch. The 15 scores are not independent, because the training sets overlap heavily. The usual standard error, std / sqrt(k), is therefore too small, and it makes small gaps look significant. The Nadeau and Bengio correction in the code replaces 1/k with 1/k + n_test/n_train, which widens the interval. Treat it as a rough guide, not a formal test. A sensible rule is that the mean difference should be clearly larger than about twice the corrected standard error. Even then, ask whether the gap matters for your use.
Give each model the same tuning effort
A tuned model beats an untuned one almost every time. If gradient boosting got 50 search iterations and logistic regression got defaults, you have measured the tuning gap and not the model gap.
Two practical ways to equalize effort:
- Give each candidate the same number of search iterations, or the same wall-clock budget.
- Tune each candidate inside the outer loop, as in nested cross-validation. The outer score then estimates the whole procedure, "tune, then fit", on data that tuning never saw.
Scores that come from a search's best_score_ are optimistic. The search picked the best of many tries on those same folds, so that number contains selection bias. Use the outer score for comparison. The earlier chapter on tuning showed this setup with RandomizedSearchCV wrapped in cross_val_score.
Models differ in how much tuning they need. Logistic regression has one or two important settings, such as regularization strength. Gradient boosting has several that interact. Equal iteration counts are not perfectly equal in value, so note the budget you used when you report results.
Compare on more than one axis
The highest score is one column in a table. Record the others at the same time:
| Quantity | Why it matters | Where to get it |
|---|---|---|
| Primary metric, mean and spread | Main accuracy claim | `cross_validate` test scores |
| Paired difference vs. baseline | Shows real lift | Subtract fold scores |
| Fit time | Retraining cost | `fit_time` in `cross_validate` |
| Predict time | Serving latency | `score_time`, or time `predict` yourself |
| Secondary metrics | Catches trade-offs such as recall | `scoring` as a dict |
You can request several metrics in one call: scoring={"auc": "roc_auc", "ap": "average_precision"}. All metrics are then computed on the same folds.
If two models are within noise of each other, choose the simpler, faster, or more interpretable one. The next chapter covers those constraints in detail.
Common errors
| Error | Effect | Fix |
|---|---|---|
| Different or unseeded splits per model | Gaps reflect the split | One seeded splitter object |
| Fitting the scaler or imputer before the split | Leakage inflates every score | Preprocessing inside a pipeline |
| Reporting `best_score_` from a search | Optimistic by selection | Nested cross-validation |
| Unequal tuning budget | Measures effort, not model | Same iterations or time |
| Choosing the metric after seeing results | Cherry-picking | Fix the primary metric first |
| Comparing means without spread | Treats noise as signal | Paired differences and standard error |
| Reusing the final test set to pick models | Test set stops being unseen | Keep it for one last check |
Preprocessing also needs care when models need different inputs. Linear models and neural networks want scaled numeric inputs. Tree models do not. Give each candidate the preprocessing it needs, but fit it inside the pipeline, and describe the choice in your report. Do not hand-tune the preprocessing for one candidate only.
A short reporting checklist
Before you declare a winner, check that your notes include:
- The splitter, number of folds, repeats, and seed.
- The primary metric and any secondary ones.
- The tuning budget per candidate.
- Mean, spread, and paired difference against the baseline.
- Fit and predict time.
- The reason you chose the final model, including any constraint that broke a tie.
Exercise
Model A scores a mean ROC AUC of 0.862 and model B scores 0.858 on the same 15 repeated folds. The paired per-fold differences (A minus B) have a standard deviation of 0.010. Using the corrected standard error from this chapter with 5-fold CV (ntest/ntrain = 0.25), is the 0.004 gap clearly larger than noise? If not, what should you do?
Show answer
The corrected standard error is sqrt((1/15 + 0.25) 0.010^2) = sqrt(0.3167 0.0001) ≈ 0.0056. The mean difference of 0.004 is smaller than one standard error, so it is well within noise. You should not claim that A is better. Prefer whichever of the two is simpler, faster, or easier to interpret and maintain.