Sub topic 13
Comparing models fairly
This chapter assumes you can build a scikit-learn pipeline, understand cross-validation, and have already set a baseline. Here you compare several candidate models so that the differences you see come from the models and not from the evaluation setup.
What "fair" means
A comparison is fair when every candidate gets the same:
- Data and features, with preprocessing fitted inside each fold.
- Folds, so each model is trained and tested on identical rows.
- Metric, chosen before you look at results.
- Tuning effort, so one model is not hand-tuned while another uses defaults.
If any of these differ, a gap in scores may reflect the setup and not the model.
Scoring candidates on identical folds
The code below reuses X, y, preprocess, and cv from the baseline chapter. Passing the same cv object means every model sees the same splits.
import numpy as np
import pandas as pd
from sklearn.compose import ColumnTransformer
from sklearn.ensemble import HistGradientBoostingClassifier, RandomForestClassifier
from sklearn.impute import SimpleImputer
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import StratifiedKFold, cross_val_score
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 = StratifiedKFold(n_splits=5, shuffle=True, random_state=0)
candidates = {
"logreg": make_pipeline(preprocess, LogisticRegression(max_iter=1000)),
"random_forest": make_pipeline(preprocess, RandomForestClassifier(n_estimators=200, random_state=0)),
"hist_gb": make_pipeline(preprocess, HistGradientBoostingClassifier(random_state=0)),
}
for name, model in candidates.items():
scores = cross_val_score(model, X, y, cv=cv, scoring="roc_auc")
print(f"{name}: {scores.mean():.3f} +/- {scores.std():.3f}")Each line prints the mean ROC AUC across the five folds and the standard deviation. The target here is an XOR-style interaction between age and city, so you should expect the tree models to beat the logistic regression, which cannot represent interactions without extra features.
Reading the differences
A higher mean is not automatically a win. Look at the spread across folds.
- If two models differ by less than one standard deviation, treat them as tied.
- Compare models fold by fold. If one model wins on every fold, the evidence is stronger than a gap in the means suggests.
- With few rows, fold scores are noisy. Repeated cross-validation (
RepeatedStratifiedKFold) gives more estimates per model.
When models are tied, choose by the practical criteria in the next chapter: simplicity, speed, and interpretability.
Common errors
- Different folds per model. Using
cv=5with shuffling and no fixed seed gives each model different splits. - Tuning one model only. A tuned gradient booster beating a default logistic regression says little. Give each candidate a comparable search budget.
- Reusing tuning scores as the final estimate. The best score from a search is optimistically biased. Use nested cross-validation, where the search runs inside each outer fold, to estimate how the whole tuning procedure performs.
- Picking the winner after many looks. The more models and metrics you try, the more likely the top score is partly luck. Keep a final holdout set for one last check.
Exercise
Two models score 0.912 +/- 0.020 and 0.905 +/- 0.018 ROC AUC on the same five folds. The first wins on three folds and loses on two. Which should you pick on score alone, and why?
Show answer
Neither is clearly better. The gap of 0.007 is smaller than either standard deviation, and the first model does not win on every fold. Treat them as tied and decide using interpretability, latency, and maintenance cost.