Sub topic 14
How noisy is the estimate? Repeating nested cross-validation
This chapter assumes you can already run nested cross-validation with GridSearchCV inside cross_val_score. It also assumes you know what inner and outer loops are, and that you have seen per-fold scores printed. Here the question is how much to trust the single number you get at the end.
One nested run is one random draw
Nested cross-validation returns a mean of outer-fold scores. That mean depends on one random partition of the data into outer folds, and on one random partition of each outer training set into inner folds. Change random_state and you get a different mean. The mean you report is an estimate with its own spread.
Two things set that spread:
- Split randomness. Which rows land in which fold changes both the outer scores and the hyperparameters the inner search picks. Repeating the procedure with new splits reduces this part.
- Finite data. Your dataset is one sample from the population. If you had collected 569 different patients, the true performance of your procedure on new data would differ. No amount of re-splitting removes this part.
Keeping the two apart tells you what repetition can and cannot do.
Measuring split noise by repeating the whole procedure
The most direct check is to rerun nested cross-validation with different seeds for both loops and look at the spread of the resulting means.
import numpy as np
from sklearn.datasets import load_breast_cancer
from sklearn.model_selection import GridSearchCV, StratifiedKFold, cross_val_score
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.svm import SVC
X, y = load_breast_cancer(return_X_y=True)
pipe = make_pipeline(StandardScaler(), SVC())
param_grid = {"svc__C": [0.1, 1, 10], "svc__gamma": ["scale", 0.01, 0.001]}
repeat_means = []
for seed in range(10):
inner_cv = StratifiedKFold(n_splits=5, shuffle=True, random_state=seed)
outer_cv = StratifiedKFold(n_splits=5, shuffle=True, random_state=1000 + seed)
search = GridSearchCV(pipe, param_grid, cv=inner_cv)
scores = cross_val_score(search, X, y, cv=outer_cv)
repeat_means.append(scores.mean())
print(f"seed {seed}: mean accuracy {scores.mean():.3f}")
repeat_means = np.array(repeat_means)
print(f"mean of means: {repeat_means.mean():.3f}")
print(f"std of means: {repeat_means.std(ddof=1):.4f}")The standard deviation of the ten means is the split noise of a single nested run. If it is 0.004, a single run could land a few thousandths away from the long-run average just because of how the rows were shuffled. If it is 0.02, a difference of one percentage point between two models cannot be told apart from reshuffling.
Using a repeated outer splitter
Rewriting the loop by hand is useful for understanding, but scikit-learn provides RepeatedStratifiedKFold (and RepeatedKFold) for the outer loop. Passing it to cross_val_score returns n_splits * n_repeats scores, ordered repeat by repeat.
import numpy as np
from sklearn.datasets import load_breast_cancer
from sklearn.model_selection import (
GridSearchCV,
RepeatedStratifiedKFold,
StratifiedKFold,
cross_val_score,
)
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.svm import SVC
X, y = load_breast_cancer(return_X_y=True)
n_splits, n_repeats = 5, 10
inner_cv = StratifiedKFold(n_splits=5, shuffle=True, random_state=1)
outer_cv = RepeatedStratifiedKFold(
n_splits=n_splits, n_repeats=n_repeats, random_state=2
)
pipe = make_pipeline(StandardScaler(), SVC())
param_grid = {"svc__C": [0.1, 1, 10], "svc__gamma": ["scale", 0.01, 0.001]}
search = GridSearchCV(pipe, param_grid, cv=inner_cv)
scores = cross_val_score(search, X, y, cv=outer_cv, n_jobs=-1)
by_repeat = scores.reshape(n_repeats, n_splits)
repeat_means = by_repeat.mean(axis=1)
print(f"overall mean: {scores.mean():.3f}")
print(f"std across repeat means: {repeat_means.std(ddof=1):.4f}")
print(f"mean within-repeat fold std: {by_repeat.std(axis=1, ddof=1).mean():.4f}")The reshape is valid because the repeated splitter yields all folds of repeat 0, then all folds of repeat 1, and so on. The two spread figures answer different questions:
| Quantity | What it describes |
|---|---|
| Std across repeat means | How much the headline number moves when you only change the splits |
| Std of folds within a repeat | How much performance varies between different test subsets of the data |
The second is usually much larger than the first. Each outer fold holds only about a fifth of the data, so single-fold scores are noisy even when the average over folds is stable.
Why the naive standard error is too small
With 50 scores, it is tempting to compute scores.std() / np.sqrt(50) and report a tight interval. That figure is wrong for two reasons.
- Scores from different folds share training data. Two folds in the same repeat train on about 60% identical rows, so their errors are positively correlated.
- Scores from different repeats use the same rows. Repeat 7 does not add new patients, only a new arrangement of the same ones.
Treating the 50 numbers as independent counts the same information many times. The resulting interval is too narrow, and the error grows as you add repeats, because the standard error shrinks toward zero while the real uncertainty about new data does not.
If you need a defensible interval or a significance test between two models, use a method designed for correlated resampling scores, such as the corrected resampled t-test of Nadeau and Bengio. It inflates the variance by a term that depends on the test-to-train ratio. For routine reporting, a safer habit is to give the mean, the fold-to-fold standard deviation, and the number of repeats, and to describe differences smaller than that spread as unresolved.
Variance of the chosen hyperparameters
Repetition also shows how stable the selection itself is. If you collect best_params_ from every outer fold across repeats, you can count how often each candidate wins. A grid where one setting wins 45 of 50 times tells a clean story. A grid where three settings split the wins roughly evenly says the score surface is flat in that region. The tuning does not matter much, and the final model will not be sensitive to which one is chosen.
To collect these, use cross_validate with return_estimator=True. Each returned estimator is a fitted GridSearchCV:
from sklearn.model_selection import cross_validate
results = cross_validate(search, X, y, cv=outer_cv, return_estimator=True, n_jobs=-1)
for est in results["estimator"][:5]:
print(est.best_params_)Keep the number of stored estimators in mind. Each holds a refit pipeline, which is cheap here but large for big models.
Cost and how many repeats to use
Repeating multiplies the cost. For a grid with 9 candidates, 5 inner folds, 5 outer folds, and 10 repeats, the fit count is 10 × 5 × (9 × 5 + 1) = 2,300 fits, plus scoring. Ten times the cost of one nested run buys a spread estimate and a more stable mean.
Practical guidance:
- Three to five repeats are enough to see whether split noise is a concern. Ten gives a steadier picture.
- If one run takes hours, use repeats on a smaller grid or a subsample to measure the noise level, then do a single full run.
- Repeating the outer loop with a fixed inner splitter is cheaper to reason about. Changing the inner seed per repeat, as in the first example, also captures variation in selection, and it costs the same.
- Use
n_jobs=-1oncross_val_scoreso the parallelism sits on the outer folds. Avoid putting it on bothGridSearchCVandcross_val_score, which oversubscribes your cores.
What repetition does not fix
Repeated nested cross-validation estimates the performance of your whole tuning procedure with less split noise. It does not remove bias from other sources:
- Leakage from preprocessing done outside the pipeline.
- Using splitters that ignore groups or time order, so that test folds resemble training folds more than future data will.
- A dataset that differs from the data the model will meet in production.
All of these stay the same however many times you repeat. Grouped and time-ordered data need a matching splitter in both loops before repetition is worth the cost. RepeatedStratifiedKFold has no grouped equivalent, so for grouped data you shuffle group assignments yourself with GroupKFold or StratifiedGroupKFold(shuffle=True) and a loop over seeds.
Exercise
You run nested cross-validation with 5 outer folds and 10 repeats and get 50 scores with a standard deviation of 0.02. A colleague reports a 95% interval of mean ± 1.96 × 0.02 / sqrt(50). Give two reasons this interval is too narrow, and say which part of the uncertainty extra repeats would reduce.
Show answer
The 50 scores are not independent. Folds within a repeat share most of their training rows, and different repeats reuse the same rows, so the effective sample size is far below 50. Dividing by sqrt(50) therefore understates the standard error, and the understatement worsens as repeats are added. Extra repeats reduce only the split noise, meaning the variation from how rows are shuffled into folds. They cannot reduce the uncertainty that comes from the dataset being one finite sample of the population.
Exercise
In the repeated outer splitter example, the scores array has shape (50,). Why is scores.reshape(n_repeats, n_splits) the right reshape, and what would go wrong with reshape(n_splits, n_repeats)?
Show answer
The repeated splitter yields all folds of repeat 0 first, then all folds of repeat 1, and so on, so consecutive blocks of nsplits scores belong to one repeat. Reshaping to (nrepeats, nsplits) puts each repeat in a row, so the row mean is that repeat's mean. Reshaping to (nsplits, n_repeats) would mix folds from different repeats in each row, and the row means would not correspond to any complete nested run.