Sub topic 15
Alternatives and when nested cross-validation is not enough
This chapter assumes you can already run nested cross-validation with GridSearchCV inside cross_val_score. It also assumes you know why the best inner score is optimistic. Here you will compare nested cross-validation with cheaper or simpler designs, and see which problems it does not solve.
What nested cross-validation actually gives you
Nested cross-validation estimates the performance of a procedure: "run this search on a training set, then fit the winner." It does not estimate the performance of one particular fitted model. Each outer fold may pick different hyperparameters, and none of those fold models is the model you ship.
That is a deliberate trade. The number answers "if I repeat my whole tuning recipe on fresh data of this size, how well will the result do?" It does not say that the final model scores exactly that. Keep this in mind when you choose between the alternatives below.
Alternatives
A held-out test set plus ordinary cross-validation
Split off a test set first. Tune with cross-validation on the remaining data only. Score the chosen model on the test set exactly once.
from sklearn.datasets import load_breast_cancer
from sklearn.model_selection import GridSearchCV, StratifiedKFold, train_test_split
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)
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.25, stratify=y, random_state=0
)
cv = StratifiedKFold(n_splits=5, shuffle=True, random_state=1)
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=cv)
search.fit(X_train, y_train)
print("CV best_score_ (optimistic):", round(search.best_score_, 3))
print("held-out test score:", round(search.score(X_test, y_test), 3))The test score is honest for this specific fitted model. It costs one search instead of an outer loop of searches. The price is data: the test set is never used for training, and with a few hundred rows a 25% test set is a noisy measurement. A test set of 100 examples with accuracy near 0.95 has a standard error of about 2 percentage points from sampling alone.
Train, validation, and test splits
With a large dataset you can replace inner cross-validation with a single validation set. Train candidates on the training part, choose on the validation part, and report on the test part. This is the cheapest option and works well when each split holds tens of thousands of examples. With small data, a single validation split makes the choice of hyperparameters noisy.
Repeated nested cross-validation
If the nested estimate varies a lot when you change the random seeds, repeat the whole procedure with different outer splits and average. This reduces the noise from one particular partition. It does not remove the other limits described below. It multiplies the cost by the number of repeats.
Cheaper searches inside the inner loop
You can keep the nested structure and make the inner search cheaper. RandomizedSearchCV samples a fixed number of candidates instead of trying all of them. HalvingGridSearchCV (still behind from sklearn.experimental import enable_halving_search_cv) discards weak candidates early. Both can be passed to cross_val_score exactly like GridSearchCV. Nesting stays honest because the outer test fold is still never seen by the search.
Comparison
| Design | What the score describes | Relative cost | Good fit |
|---|---|---|---|
| Best score from `GridSearchCV` | Nothing reliable (optimistic) | 1x | Only for choosing hyperparameters, never for reporting |
| Test set plus cross-validated search | One specific fitted model | About 1x | Large or medium data, one final model |
| Train/validation/test | One specific fitted model | Lowest | Very large data |
| Nested cross-validation | The whole tuning procedure | Outer folds x one search | Small or medium data, comparing procedures |
| Repeated nested cross-validation | The procedure, with less split noise | Repeats x nested | Small data, high-stakes comparisons |
A decision path
Where nested cross-validation is not enough
Nested cross-validation fixes one specific bias: selecting hyperparameters on the same folds that score them. It does not fix the problems below.
The outer folds can still be overused
The outer folds are only unseen if you look at them once. Suppose you run nested cross-validation, see a poor score, change the features, and run it again. Repeat that ten times. You are now selecting a pipeline design on the outer folds, and the final score is optimistic again, only more slowly. The same happens if you compare twenty algorithms by their nested scores and report the winner's score. Treat the nested score as a measurement you take rarely. If you need a lot of iteration, keep a separate final test set that you touch once at the end.
Leakage from steps outside the pipeline
Nested cross-validation protects only the steps that run inside the folds. Scaling, imputation, feature selection, target encoding, and oversampling must all be in the Pipeline that the search clones. A feature selector fitted on all the data before the loops starts makes the outer score optimistic by a large margin, and nesting does nothing about it. The same holds for duplicate rows or near-duplicates that land in both training and test folds. Deduplicate before splitting, or use grouped splits.
Splits that do not match the data
Random folds assume rows are exchangeable. Patients with several visits, sensors with many readings, or text from the same author violate that. Use GroupKFold or StratifiedGroupKFold for both the inner and outer loops. For time series, random folds let the model train on the future. Use time-ordered splits in both loops:
import numpy as np
from sklearn.linear_model import Ridge
from sklearn.model_selection import GridSearchCV, TimeSeriesSplit, cross_val_score
rng = np.random.default_rng(0)
X = rng.normal(size=(300, 5))
y = X @ np.array([1.0, 0.5, 0.0, 0.0, -1.0]) + rng.normal(scale=0.5, size=300)
inner = TimeSeriesSplit(n_splits=3)
outer = TimeSeriesSplit(n_splits=4)
search = GridSearchCV(Ridge(), {"alpha": [0.01, 0.1, 1, 10]}, cv=inner)
scores = cross_val_score(search, X, y, cv=outer, scoring="neg_mean_squared_error")
print("outer MSE per fold:", np.round(-scores, 3))Note that TimeSeriesSplit makes the first outer training set small, so the earliest fold is a weak measurement. It also does not prepare you for a change in the data-generating process after deployment.
The spread is not a trustworthy confidence interval
The outer scores come from overlapping training sets, so they are correlated. The standard deviation of the fold scores therefore understates the real uncertainty in the mean. Dividing by the square root of the number of folds, as you would for independent samples, gives intervals that are too narrow. Bengio and Grandvalet (2004) showed that no unbiased estimator of the variance of k-fold cross-validation exists. Report the mean and the range of the fold scores, and avoid claims of statistical significance based on a naive t-test over folds. If you must compare two procedures, use the same outer splits for both and look at the paired per-fold differences.
Small data limits everything
With 60 examples, each outer test fold holds around 12. One misclassified example moves that fold by 8 percentage points. Nesting gives an honest number, but the number may be too noisy to support a decision. More repeats help only a little, because they reuse the same 60 rows.
Distribution shift
Every cross-validation scheme assumes that future data resembles the data you split. A hospital model validated on one site's records can fail at another site. Nested cross-validation measures nothing about this. Test on data from a different time, site, or source if you can get it.
Tuning choices that are not hyperparameters
The inner search covers only the grid you wrote. The choices you made before it, such as the metric, the class of model, the features you decided to keep after looking at the whole dataset, and the grid ranges, are outside the loop. If you shaped those by looking at all the data, some of that information has leaked into the outer folds.
A practical checklist
- Put every data-dependent step inside one
Pipeline. - Choose splitters for the inner and outer loops that match the data structure.
- Decide the full list of candidate procedures before the first nested run.
- Run the nested estimate rarely, and repeat it with new outer splits if the result drives a decision.
- Report the mean, the per-fold range, and the hyperparameters chosen per fold.
- For a high-stakes final claim, confirm on a test set or external data that nothing has touched.
Exercise
You have 400 labeled rows. You tune an SVM with a grid search, run nested cross-validation, get 0.91, change the feature set because the score seemed low, rerun, and get 0.94. You report 0.94. Name the problem and two ways to fix the evaluation.
Show answer
The outer folds were reused to choose the feature set, so 0.94 is optimistic again: you selected a pipeline design on the data that was supposed to be unseen. One fix is to hold out a final test set before any tuning and score the chosen pipeline on it once. Another is to move the feature-set choice inside the inner search, for example as a grid parameter in the pipeline, so the outer folds do not influence it. Repeating nested cross-validation with fresh outer splits helps with noise but does not remove this selection effect.
Exercise
Why is the standard deviation of the five outer-fold scores a poor basis for a 95% confidence interval on the true performance?
Show answer
The outer training sets overlap, so the fold scores are positively correlated and the spread understates the real uncertainty. Bengio and Grandvalet showed that no unbiased estimator of the variance of k-fold cross-validation exists. Report the range of fold scores and compare procedures with paired differences on identical splits instead.