Sub topic 12
Repeated Cross-Validation
This chapter assumes you know how k-fold and stratified k-fold work, how to build a scikit-learn pipeline, and how to read a list of fold scores. Repeated cross-validation runs k-fold several times, each time with a different random partition, and pools the results. It makes the score estimate less dependent on one lucky or unlucky split.
Why one k-fold run is still noisy
K-fold removes the worst weakness of a single holdout split, because every sample is tested once. But with shuffle=True, the result still depends on which samples the shuffle puts in the same fold. A different seed gives a different partition and a different mean score.
The following script shows this on one dataset and one model. Only the seed changes.
from sklearn.datasets import load_breast_cancer
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 StandardScaler
X, y = load_breast_cancer(return_X_y=True)
model = make_pipeline(StandardScaler(), LogisticRegression(max_iter=1000))
for seed in range(5):
cv = StratifiedKFold(n_splits=5, shuffle=True, random_state=seed)
scores = cross_val_score(model, X, y, cv=cv)
print(f"seed={seed} mean={scores.mean():.4f}")The five means will not be identical. The spread is small on a clean dataset like this one. On small or noisy datasets, it can be larger than the difference between two models you are trying to compare.
How repeated cross-validation works
Repeated cross-validation wraps the k-fold procedure in an outer loop of n_repeats iterations. Each iteration reshuffles the data, builds a new set of k folds, and scores every fold. You end up with n_splits * n_repeats scores.
Scikit-learn provides two classes:
| Class | Inner splitter | Use for |
|---|---|---|
| `RepeatedKFold` | `KFold` | Regression, or classification with balanced classes |
| `RepeatedStratifiedKFold` | `StratifiedKFold` | Classification, especially with imbalanced classes |
Both take n_splits, n_repeats, and random_state. You pass the object as the cv argument, exactly as you would pass a plain KFold.
Running it and reading the results
The scores come back in order: all folds of repeat 1, then all folds of repeat 2, and so on. That ordering lets you reshape the array into a repeats-by-folds grid.
import numpy as np
from sklearn.datasets import load_breast_cancer
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 = load_breast_cancer(return_X_y=True)
model = make_pipeline(StandardScaler(), LogisticRegression(max_iter=1000))
n_splits, n_repeats = 5, 3
cv = RepeatedStratifiedKFold(n_splits=n_splits, n_repeats=n_repeats, random_state=0)
scores = cross_val_score(model, X, y, cv=cv, scoring="accuracy")
print("number of scores:", len(scores))
grid = scores.reshape(n_repeats, n_splits)
print("mean per repeat:", grid.mean(axis=1).round(4))
print(f"overall mean={scores.mean():.4f} std={scores.std(ddof=1):.4f}")The mean per repeat shows how much a single k-fold run would have moved. The overall mean is your estimate, and it is more stable than any single repeat.
The pipeline matters here. Each of the 15 fits refits the scaler on its own training portion, so repeating the procedure does not add leakage. Repeating a leaky procedure only gives you a more precise wrong answer.
What the extra repeats do and do not buy
Repeating reduces one kind of variance: the variance caused by the random partition. It does not change two other things.
- Bias. Each model still trains on
(k-1)/kof the data. The bias discussed in the chapter on choosing k stays the same. If you want less bias, change k. - Sampling variance of the dataset. Your dataset is one finite sample from the world. No reshuffling creates new information. The repeats reuse the same samples, so the score uncertainty from having only n samples remains.
This leads to a common mistake: treating the pooled scores as independent measurements. They are not. Training sets overlap heavily within a repeat and across repeats, and the same samples appear in many test folds. The plain standard error std / sqrt(len(scores)) is therefore far too small, and it shrinks as you add repeats even though your real knowledge has not improved.
A more honest standard error
Nadeau and Bengio proposed a correction for resampled scores. The variance of the mean is estimated as
(1/J + n_test/n_train) * s^2
where J is the number of scores, s^2 is their sample variance, and n_test/n_train is the size ratio of one test fold to its training set. For k-fold, that ratio is 1/(k-1).
import numpy as np
from sklearn.datasets import load_breast_cancer
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 = load_breast_cancer(return_X_y=True)
model = make_pipeline(StandardScaler(), LogisticRegression(max_iter=1000))
k, repeats = 5, 3
cv = RepeatedStratifiedKFold(n_splits=k, n_repeats=repeats, random_state=0)
scores = cross_val_score(model, X, y, cv=cv)
J = len(scores)
s2 = scores.var(ddof=1)
naive_se = np.sqrt(s2 / J)
corrected_se = np.sqrt((1 / J + 1 / (k - 1)) * s2)
print(f"mean={scores.mean():.4f}")
print(f"naive SE={naive_se:.4f} corrected SE={corrected_se:.4f}")The corrected value is several times larger than the naive one. Notice what the formula implies. As J grows, the 1/J term vanishes, but the n_test/n_train term stays. More repeats cannot push the uncertainty below that floor.
Comparing two models
Repeated cross-validation is most useful when you compare candidates whose scores are close. Two rules make the comparison fair.
- Use identical splits for both models. Create one
cvobject with an integerrandom_stateand pass it to everycross_val_scorecall. Withrandom_state=None, each call to the splitter draws new random partitions, so the models would be tested on different folds. - Compare scores in pairs. Because the folds match, you can subtract the two score arrays element by element and study the differences. The differences are less noisy than the raw scores, since fold difficulty cancels out.
from sklearn.datasets import load_breast_cancer
from sklearn.ensemble import RandomForestClassifier
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 = load_breast_cancer(return_X_y=True)
cv = RepeatedStratifiedKFold(n_splits=5, n_repeats=3, random_state=42)
linear = make_pipeline(StandardScaler(), LogisticRegression(max_iter=1000))
forest = RandomForestClassifier(n_estimators=100, random_state=0)
a = cross_val_score(linear, X, y, cv=cv, n_jobs=-1)
b = cross_val_score(forest, X, y, cv=cv, n_jobs=-1)
diff = a - b
print(f"linear={a.mean():.4f} forest={b.mean():.4f}")
print(f"mean difference={diff.mean():.4f} std of differences={diff.std(ddof=1):.4f}")If the mean difference is small compared with the standard deviation of the differences, the data do not separate the models. Use the corrected variance formula on diff before claiming one is better.
Cost and how to choose the settings
Every repeat multiplies the training cost. The number of model fits is n_splits * n_repeats. Going from 5-fold to 10 repeats of 5-fold means 50 fits.
Some practical defaults:
- Start with 5 or 10 folds and 3 to 10 repeats. Common choices are 10 folds with 3 repeats, or 5 folds with 5 to 10 repeats.
- Use more repeats when the dataset is small, since small data makes the partition matter more, and when the model is cheap to train.
- Use fewer repeats, or none, when a single fit takes minutes. A single k-fold run on a large dataset is usually stable already, because the partition affects the result less when each fold holds thousands of samples.
- Pass
n_jobs=-1tocross_val_scoreto run the fits in parallel.
A rough way to judge whether you need repeats: run two or three different seeds of plain k-fold, as in the first script. If the means differ by less than the gap you care about, repeating adds cost without changing your decision.
When repeating does not apply
- Plain
KFoldwithout shuffling. The partition is deterministic, so every repeat would be identical. TheRepeated*classes shuffle internally, so this only matters if you build your own loop. TimeSeriesSplit. The splits follow time order and are fixed. There is nothing to randomize.GroupKFold. It is deterministic as well. If you need repeated group-aware splits, useStratifiedGroupKFold(shuffle=True)inside a loop with different seeds, orGroupShuffleSplitwith many splits. The scikit-learnRepeated*classes do not take agroupsargument.- Hyperparameter tuning. Running a grid search with a repeated splitter gives a steadier choice of parameters. It does not make the best score an unbiased estimate. For that you still need nested cross-validation, with the repeated splitter in the outer loop if you want the extra stability.
Common errors
- Using
RepeatedKFoldon imbalanced classification and getting folds with very few positive samples. UseRepeatedStratifiedKFold. - Leaving
random_stateunset and then being unable to reproduce a result or compare two models on the same folds. - Concluding that more repeats make the model better. Repeats change the precision of the estimate, not the model.
- Reporting a very narrow interval built from the naive standard error.
Exercise
You run RepeatedStratifiedKFold(n_splits=10, n_repeats=5, random_state=0) on a pipeline with 500 samples. How many times is the model fit, and how many samples are in each test fold?
Show answer
The model is fit 10 * 5 = 50 times. Each test fold holds about 500 / 10 = 50 samples (stratification may shift the count by one), and each training set holds about 450.
Exercise
A colleague reports 15 scores from 5-fold with 3 repeats, with a standard deviation of 0.02. They quote a standard error of 0.02 / sqrt(15) = 0.005. Using the Nadeau-Bengio formula, what is the corrected standard error, and why is their number too small?
Show answer
The corrected variance is (1/15 + 1/4) 0.02^2 = 0.3167 0.0004 = 0.0001267, so the corrected standard error is about 0.0113, more than twice their 0.005. Their number is too small because the 15 scores are not independent. Training sets overlap and the same samples are tested repeatedly, so the effective number of independent measurements is much lower than 15.