Sub topic 9
Tuning Leakage and Nested Cross-Validation
This chapter assumes you know how to build a scikit-learn pipeline and run cross_val_score. It also assumes you understand why preprocessing must be fit inside each training fold. Here the leak comes from the choices you make about the model, not from the features.
How tuning leaks
Every time you look at a score and then change something, you use that score to make a decision. Hyperparameters (settings such as C in an SVM), feature sets, and model families all count. If the same data produces the score and also guides the choice, the final number is optimistic. This is tuning leakage.
Two patterns are common:
- Test set reuse. You train, check the test score, adjust the model, and check again. After many rounds the test set has shaped the model, even though no test row was ever used for fitting.
- Reporting the search score.
GridSearchCVexposesbest_score_. That score is the maximum over all candidate settings. A maximum of noisy estimates is biased upward, so it overstates how the chosen model will do on new data.
The more candidates you try, the larger the bias. It is worst when the dataset is small and the search space is large.
Fixing it with a three-way split
The simplest fix is to keep a test set you touch once.
- Split off a test set and leave it alone.
- Tune on the remaining data, using cross-validation or a validation split.
- Refit the chosen model on all of the non-test data.
- Score on the test set one time and report that number.
If the test score disappoints, resist the urge to tune again. Doing so turns the test set into a second validation set. If you must iterate, collect fresh data or accept that the estimate is now less trustworthy.
A single test split is noisy when data is scarce. That is where nested cross-validation helps.
Nested cross-validation
Nested cross-validation uses two loops.
- The inner loop picks hyperparameters. It runs only on the training part of the current outer fold.
- The outer loop estimates performance. Its test folds never take part in the inner search.
The outer score therefore measures the whole procedure: "run a grid search, then fit the winner." It does not measure one particular model.
Nested CV in scikit-learn
GridSearchCV is itself an estimator. Passing it to cross_val_score gives you nested cross-validation.
from sklearn.datasets import make_classification
from sklearn.model_selection import GridSearchCV, KFold, cross_val_score
from sklearn.svm import SVC
X, y = make_classification(n_samples=200, random_state=0)
inner = KFold(n_splits=3, shuffle=True, random_state=1)
outer = KFold(n_splits=5, shuffle=True, random_state=2)
search = GridSearchCV(SVC(), {"C": [0.1, 1, 10]}, cv=inner)
scores = cross_val_score(search, X, y, cv=outer)
print(scores.mean())In each of the 5 outer iterations, GridSearchCV fits on the outer training rows and runs its own 3-fold search there. The outer test rows played no part in choosing C, so scores.mean() is an honest estimate of the tuned procedure.
Nested cross-validation fits many models. Here that is 5 × (3 × 3 + 1) = 50 fits. Cost grows quickly with larger grids, so use n_jobs or RandomizedSearchCV when needed.
Common errors
- Tuning on the full dataset, then cross-validating the winner. The hyperparameters have already seen every row, so the cross-validation scores are inflated.
- Putting preprocessing outside the search. Wrap the scaler or selector and the model in a
Pipeline, then tune the pipeline. Otherwise each inner fold leaks, as covered in earlier chapters. - Comparing models by outer scores, then picking the best. Choosing among several nested results is another round of selection. Treat the gap between close scores as noise.
- Reusing the same fold seeds everywhere. Identical splits for inner and outer loops can correlate the two. Use different
random_statevalues, as the example does. - Ignoring structure. If rows are grouped or ordered in time, both loops need
GroupKFoldorTimeSeriesSplit. PlainKFoldbrings back group and temporal leakage.
When to use which approach
| Situation | Suggested approach |
|---|---|
| Plenty of data, few tuning rounds | Train, validation, and test split |
| Small data, a real grid search | Nested cross-validation |
| Large search or slow model | Single test split, with a limited search budget |
| Time-ordered or grouped rows | Nested CV with time-aware or group-aware splitters |
Exercise
A teammate runs GridSearchCV on the full dataset with 5-fold CV and reports bestscore as the expected production accuracy. Give two reasons the number is optimistic and one way to get an honest estimate.
Show answer
First, bestscore is the maximum across all candidate settings, so noise in the fold scores biases it upward. Second, every row, including those in each validation fold, was used to pick the hyperparameters, so the score was never measured on data untouched by the choice. For an honest estimate, either hold out a test set that is scored once after tuning, or wrap the GridSearchCV in an outer crossvalscore (nested cross-validation).
Exercise
In the nested example, 5 outer folds, 3 inner folds, and 3 values of C are used. How many model fits happen, counting the refit of the best model in each outer iteration?
Show answer
Each outer iteration runs 3 inner folds for each of 3 values of C, giving 9 fits, plus 1 refit of the best model. That is 10 fits per outer fold, so 5 × 10 = 50 fits in total.