Sub topic 7
Repeated cross-validation for fair comparisons
This chapter assumes you know how to split data into training and test sets, how to use scikit-learn estimators, and what a standard deviation is. The previous chapters covered metric choice and leakage.
Why a single split is not enough
A single train/test split gives one score. That score depends on which rows landed in the test set. With a 5% minority class, a different random split can move the score by several points. If you compare a baseline and a candidate on one split, you may be measuring luck.
Cross-validation reduces this problem. In k-fold cross-validation, you divide the data into k folds. Each fold serves once as the test set while the model trains on the other k-1 folds. You get k scores instead of one.
Repeated cross-validation runs the whole procedure several times, each time with a different shuffle into folds. Five folds repeated three times gives 15 scores per model.
The rules for a fair comparison
- Use the same folds for every model. Both models must see identical train and test rows, so the scores can be paired fold by fold.
- Use the same metric for both models.
- Stratify classification splits, so each fold keeps the class ratio. Otherwise some folds may contain almost no minority examples.
- Fix the random seed. An integer
random_statemakes the splitter produce the same folds every time you use it.
Example: baseline against logistic regression
from sklearn.datasets import make_classification
from sklearn.dummy import DummyClassifier
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import RepeatedStratifiedKFold, cross_val_score
X, y = make_classification(n_samples=2000, weights=[0.95, 0.05], random_state=0)
cv = RepeatedStratifiedKFold(n_splits=5, n_repeats=3, random_state=0)
baseline_scores = cross_val_score(
DummyClassifier(strategy="prior"), X, y, cv=cv, scoring="balanced_accuracy"
)
model_scores = cross_val_score(
LogisticRegression(max_iter=1000), X, y, cv=cv, scoring="balanced_accuracy"
)
print("baseline:", baseline_scores.mean(), baseline_scores.std())
print("logreg: ", model_scores.mean(), model_scores.std())The same cv object is passed to both calls. Because its seed is fixed, both calls use the same 15 train/test splits, and model_scores[i] and baseline_scores[i] come from the same fold.
The mean is your estimate of performance. The std shows how much the score moves from fold to fold. A baseline with a standard deviation near zero is expected here. A constant predictor always scores 0.5 balanced accuracy, whatever the fold.
Reading the output
Compare the gap between the means with the spread of the scores. If the logistic regression mean is 0.15 above the baseline and the standard deviation is 0.02, the gap is large relative to the noise. If the gap is 0.01 and the standard deviation is 0.03, you cannot say which model is better.
Pairing helps further. Subtract the baseline score from the model score fold by fold, and look at the differences. Fold difficulty affects both models, so it largely cancels in the differences. The next chapter uses this to judge whether an improvement is real.
Common errors
- Different folds per model. Passing
cv=5to each call with shuffling and no seed gives each model different splits, so the scores cannot be paired. - Preprocessing outside the loop. If you scale or select features on the whole dataset before cross-validation, information from the test folds leaks into training. Put these steps in a
Pipelineso they are refit inside each fold. - Tuning on the same folds you report. Hyperparameter search on these folds makes the reported score optimistic. Keep a final held-out test set for the number you report.
- Too few repeats. Three to ten repeats is usually enough. More repeats make the mean steadier but do not remove the overlap problem.
Exercise
You compare a baseline and a candidate with cross_val_score, but you pass KFold(n_splits=5, shuffle=True) with no random_state to each call. Why is the comparison unfair, and how do you fix it?
Show answer
Without a seed, each call shuffles differently, so the two models are scored on different train/test splits. Differences in fold difficulty then mix with differences in model quality, and the scores cannot be paired. Create one splitter with a fixed random_state (for example RepeatedStratifiedKFold(..., random_state=0)) and pass the same object to both calls.