Sub topic 7
Repeated cross-validation for fair comparisons
A baseline comparison is only fair if both models face the same test and the score is stable enough to trust. This chapter covers how repeated cross-validation provides both. It assumes you know the following:
- How to fit and score a scikit-learn estimator.
- What a train/test split and leakage are, from the earlier chapter on splits.
- The meaning of mean, standard deviation and standard error.
Why one split is not enough
A single train/test split gives you one number. That number depends on which rows landed in the test set. With 2,000 rows and 5% positives, the test set holds about 25 positive cases (if 25% of the data is held out, that is 500 rows). Moving three of them between train and test can change recall or balanced accuracy by several points.
If you compare a baseline and a candidate on one split, you can't tell whether a gap of 0.02 reflects a better model or a lucky split. Cross-validation reduces this problem by scoring every row exactly once as test data. Repeating it with different partitions shows how much the score moves.
How k-fold cross-validation works
In k-fold cross-validation you cut the data into k folds. For each fold, you train on the other k−1 folds and score on the held-out fold. You get k scores.
Repeated k-fold runs this procedure n times, each time with a different random partition. The result is k × n scores. With 5 folds and 3 repeats, you get 15.
Two sources of noise are now visible:
- Between folds: different rows are held out.
- Between repeats: the same rows are grouped differently.
A single 5-fold run hides the second source. Repeating it exposes it.
Choosing the splitter
Pick the splitter that matches the structure of your data. The wrong one can leak information or give misleading scores.
| Situation | Splitter | Reason |
|---|---|---|
| Classification, imbalanced classes | `RepeatedStratifiedKFold` | Keeps the class ratio in every fold, so no fold has zero positives |
| Regression or balanced classes | `RepeatedKFold` | Plain shuffled folds are enough |
| Rows grouped by user, patient or device | `GroupKFold` (not repeated by default) | Keeps all rows of one group on the same side of the split |
| Time series | `TimeSeriesSplit` | Training data must come before test data |
Shuffled repeated folds on time-ordered data let the model train on the future and predict the past. That is leakage, and the scores will look better than reality.
Comparing a baseline and a model on identical folds
The key rule is to use the same cv object for every model. When you pass an integer random_state, the splitter produces the same partitions each time you use it. The fold scores of the two models then line up one to one.
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 baseline predicts the majority class every time. Its balanced accuracy is exactly 0.5 in every fold, so its standard deviation is 0. The logistic regression scores above 0.5, and its standard deviation shows how much a single fold can mislead you.
Note the scoring choice. Plain accuracy would give the baseline about 0.95, which hides everything. The metric must be chosen before the comparison, as covered in the metrics chapter.
Paired differences
Because both models used identical folds, you can subtract fold by fold. The result is one difference per fold.
diff = model_scores - baseline_scores
print("per-fold gain, first five:", diff[:5])
print("mean gain:", diff.mean())
print("std of gain:", diff.std(ddof=1))Pairing is more informative than comparing two overall means. A hard fold is hard for both models, so the difficulty cancels in the subtraction. The spread of diff is usually smaller than the spread of either score set. A consistent gain of 0.04 is much more convincing than a mean gain of 0.04 that ranges from −0.05 to +0.12 across folds.
Looking at repeat-level variation
cross_val_score returns scores in order: all folds of repeat 1, then repeat 2, and so on. You can reshape them to see how much the partitioning alone changes the result.
import numpy as np
from sklearn.datasets import make_classification
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import RepeatedStratifiedKFold, cross_val_score
n_splits, n_repeats = 5, 3
X, y = make_classification(n_samples=2000, weights=[0.95, 0.05], random_state=0)
cv = RepeatedStratifiedKFold(n_splits=n_splits, n_repeats=n_repeats, random_state=0)
scores = cross_val_score(
LogisticRegression(max_iter=1000), X, y, cv=cv, scoring="balanced_accuracy"
)
by_repeat = scores.reshape(n_repeats, n_splits)
print("mean per repeat:", by_repeat.mean(axis=1))
print("spread of repeat means:", by_repeat.mean(axis=1).std(ddof=1))If the repeat means differ by about as much as the gain you are trying to detect, one 5-fold run would not have been enough to decide anything.
Keeping preprocessing inside the folds
Any step that learns from data must be fitted only on the training part of each fold. Scalers, imputers, feature selectors and target encoders all learn from data. If you fit a scaler on the full dataset and then cross-validate, the test folds have already influenced the training data.
Wrap the steps in a Pipeline so scikit-learn refits them inside every fold:
from sklearn.datasets import make_classification
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import RepeatedStratifiedKFold, cross_val_score
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
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)
model = make_pipeline(StandardScaler(), LogisticRegression(max_iter=1000))
scores = cross_val_score(model, X, y, cv=cv, scoring="balanced_accuracy")
print(scores.mean())The same applies to the baseline. A DummyClassifier learns only class frequencies, but it should still be fitted inside the folds, which cross_val_score does for you.
Common errors
- Different splits for each model. Calling
cross_val_score(..., cv=5)for each model without fixing the shuffle can give different partitions. Create onecvobject with a seed and reuse it. - Tuning on the same folds you report. If you choose hyperparameters by the cross-validation score and then report that same score, it is optimistic. Use nested cross-validation or a separate final test set.
- Reporting only the mean. Always report the spread too. A mean of 0.81 with a standard deviation of 0.01 and a mean of 0.81 with a standard deviation of 0.08 describe very different situations.
- Ignoring groups. If one customer appears in many rows, a random split puts the same customer in train and test. Use
GroupKFold. - Wrong direction of scores. Scikit-learn scorers follow "higher is better". Error metrics appear as negative values, such as
"neg_mean_absolute_error". Flip the sign before reading them as errors.
What repeated cross-validation does not fix
Repeating the procedure lowers the noise caused by partitioning. It does not remove noise caused by the finite dataset. Every repeat uses the same rows, so 15 scores are not 15 independent measurements.
The folds overlap in training data, and different repeats reuse the same observations. The standard deviation of the scores therefore understates the real uncertainty. The next chapter builds on this when it asks whether an improvement is larger than noise. For now, treat the spread as a rough guide, not as a precise confidence interval.
Summary of the procedure
- Choose the metric first.
- Choose the splitter that matches your data structure.
- Create one seeded
cvobject. - Score the baseline and the candidate on that object, with preprocessing inside a pipeline.
- Compute fold-by-fold differences.
- Report the mean, the spread and the number of folds and repeats.
Exercise
You compare a baseline and a candidate model by calling crossvalscore with cv=KFold(nsplits=5, shuffle=True) and no randomstate, once per model. The candidate scores 0.02 higher. Give two reasons this comparison is not fair, and say what you would change.
Show answer
First, KFold with shuffle=True and no random_state produces a different partition on each call, so the two models are scored on different folds. Their fold scores cannot be paired, and part of the 0.02 gap may come from easier partitions. Second, five folds with one repeat cannot show how much the score moves when the partitioning changes, so there is no way to judge whether 0.02 is larger than the noise. Create one seeded RepeatedStratifiedKFold (or RepeatedKFold for regression) with several repeats, pass the same object to both models, and compute the per-fold differences. If the classes are imbalanced, also use a metric such as balanced accuracy instead of accuracy.
Exercise
A dataset has 10 rows per customer, and the goal is to predict behaviour for new customers. Why can ordinary repeated k-fold give an optimistic score, and which splitter should you use instead?
Show answer
Rows from the same customer can land in both the training and test folds. The model can then recognise customer-specific patterns that will not be available for new customers, which inflates the score. Use a group-aware splitter such as GroupKFold, passing the customer ID as the groups argument, so that all rows of a customer stay on one side of each split.