Sub topic 9
Tuning Leakage and Nested Cross-Validation
This chapter assumes you know how to build a scikit-learn Pipeline, how cross_val_score splits data, and why a held-out test set exists. Earlier chapters showed leakage through preprocessing and feature selection. Here the leak comes from a different place: the act of choosing hyperparameters and model settings by looking at the same scores you later report.
How tuning leaks information
A hyperparameter is a setting you choose before training, such as the regularization strength C of an SVM or the depth of a tree. You pick it by trying several values and keeping the one with the best score.
That choice is itself a form of fitting. The score you used to pick the winner is no longer an unbiased estimate of future performance, for two reasons:
- Every candidate has some noise in its score. The maximum of several noisy scores is biased upward. This is a selection effect.
- Each time you look at a score and change something, you transfer a little information about those rows into your decisions.
The more candidates you try, the larger the bias. With a handful of values the optimism is small. With hundreds of random-search draws, a wide pipeline search, or many rounds of manual tweaking, it can be large, especially on small datasets.
Three ways the test set gets reused
The same pattern shows up in three forms.
- Reporting the best cross-validation score.
GridSearchCV.best_score_is the highest mean score among the candidates. It is optimistic by construction. - Tuning on the test set. You evaluate several models on the test set, then keep the best. The test set has now served as a validation set.
- Repeated peeking. You evaluate on the test set, dislike the result, adjust features or parameters, and evaluate again. Each round leaks a little. After twenty rounds, the test set is part of your training process.
The third form is the hardest to notice because it happens across days and notebooks rather than in one function call.
A simulation: tuning on noise
You can measure the bias directly. In the next example the labels are random, so the true accuracy of any model is 0.5. We try many hyperparameter settings and report the best score.
import numpy as np
from sklearn.model_selection import GridSearchCV, KFold, cross_val_score
from sklearn.neighbors import KNeighborsClassifier
rng = np.random.default_rng(0)
X = rng.normal(size=(60, 5))
y = rng.integers(0, 2, size=60) # labels are pure noise
param_grid = {
"n_neighbors": list(range(1, 30, 2)),
"weights": ["uniform", "distance"],
"p": [1, 2],
}
inner = KFold(n_splits=5, shuffle=True, random_state=1)
search = GridSearchCV(KNeighborsClassifier(), param_grid, cv=inner)
search.fit(X, y)
print("best_score_ (optimistic):", round(search.best_score_, 3))
outer = KFold(n_splits=5, shuffle=True, random_state=2)
nested = cross_val_score(
GridSearchCV(KNeighborsClassifier(), param_grid, cv=inner), X, y, cv=outer
)
print("nested estimate:", round(nested.mean(), 3))The best_score_ is typically above 0.5, often noticeably so, even though no model can learn anything from random labels. The nested estimate stays near 0.5. The exact numbers depend on the seeds, but the direction is consistent: the selected score is biased upward and the nested score is not.
Nested cross-validation
Nested cross-validation separates the two jobs that a single cross-validation loop cannot do at once: choosing a model and estimating how good the chosen procedure is.
- The inner loop runs the hyperparameter search. It only ever sees the training portion of an outer fold.
- The outer loop scores the result on rows that played no part in the search.
The code from the topic plan expresses this in two lines. The GridSearchCV object is itself an estimator, so you pass it to cross_val_score.
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())For each of the 5 outer folds, GridSearchCV fits and cross-validates 3 candidate values of C across 3 inner splits, then refits the best one on the full outer training set. That is 5 × (3 × 3 + 1) = 50 model fits.
What nested cross-validation estimates
The nested score does not describe one particular model. Different outer folds may select different values of C. The score estimates the quality of the whole procedure: "run this search on data like this and keep the winner."
This has a practical consequence for the final model. Once you are satisfied with the estimate, run the search once on all your data and deploy that result. The nested score is the honest figure to report for it.
final = GridSearchCV(SVC(), {"C": [0.1, 1, 10]}, cv=inner).fit(X, y)
print(final.best_params_)Cost and when to use it
Nested cross-validation multiplies the training cost by roughly the number of outer folds. Use these rules of thumb.
| Situation | Reasonable approach |
|---|---|
| Large dataset, cheap model | A single train/validation/test split is usually enough |
| Small or medium dataset, need an honest estimate | Nested cross-validation |
| Expensive model, little data | Nested with fewer folds, or a smaller search space |
| Comparing several algorithms with tuning | Run the same nested loop for each, using identical outer splits |
Nested cross-validation is mainly a tool for evaluation. If you only need a good model and have a separate untouched test set, you do not need it.
The untouched test set alternative
The simpler approach is to split once into three parts and use each for one job.
| Split | Purpose | How often you may look |
|---|---|---|
| Training | Fit model parameters | Freely |
| Validation (or cross-validation inside training) | Compare settings, choose hyperparameters | Many times |
| Test | Report final performance | Once |
from sklearn.datasets import make_classification
from sklearn.model_selection import GridSearchCV, train_test_split
from sklearn.svm import SVC
X, y = make_classification(n_samples=500, random_state=0)
X_dev, X_test, y_dev, y_test = train_test_split(X, y, test_size=0.2, random_state=0)
search = GridSearchCV(SVC(), {"C": [0.1, 1, 10]}, cv=5)
search.fit(X_dev, y_dev) # tuning sees only the development rows
print("cv score (optimistic):", round(search.best_score_, 3))
print("test score (report this):", round(search.score(X_test, y_test), 3))Here search.score uses the refit best model on rows the search never saw. The rule that makes this work is discipline: you evaluate on the test set once. If you go back and change anything after seeing the result, the set is spent, and you need fresh data for an honest number.
Edge cases and common errors
- Preprocessing outside the search. If you scale or select features before calling
GridSearchCV, the earlier leakage returns inside the inner loop. Put those steps in aPipelineand pass the pipeline to the search, with parameter names likesvc__C. - Different splits for the outer loop across models. When comparing two algorithms, use the same outer folds for both. Otherwise differences can come from the split, not the model.
- Unstable selection. If the outer folds choose very different hyperparameters, the model is sensitive to the data. Inspect
cv_results_or usereturn_estimator=Trueincross_validateto see each fold's winner. - Nested loops that ignore structure. If rows come in groups or have a time order, both loops need group-aware or time-aware splitters. A plain
KFoldinner loop on grouped data leaks in the inner search even when the outer loop is correct. - Tuning the random seed. Trying many seeds for the split and keeping the best one is also tuning on the test set.
- Early stopping. Gradient boosting with early stopping monitors a validation set. If that is your test set, the stopping point leaks. Hold out a separate validation set.
Here is a pipeline version that handles the first error correctly.
from sklearn.datasets import make_classification
from sklearn.feature_selection import SelectKBest, f_classif
from sklearn.model_selection import GridSearchCV, KFold, cross_val_score
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.svm import SVC
X, y = make_classification(n_samples=300, n_features=30, random_state=0)
pipe = Pipeline([
("scale", StandardScaler()),
("select", SelectKBest(f_classif)),
("clf", SVC()),
])
grid = {"select__k": [5, 10, 20], "clf__C": [0.1, 1, 10]}
inner = KFold(n_splits=3, shuffle=True, random_state=1)
outer = KFold(n_splits=5, shuffle=True, random_state=2)
scores = cross_val_score(GridSearchCV(pipe, grid, cv=inner), X, y, cv=outer)
print(scores.mean())Scaling, feature selection, and the classifier are all refit inside every inner split, and the number of selected features k is tuned along with C.
Summary of the rules
- Any score used to choose something is biased upward for the chosen option.
- Report performance on data that took no part in any choice: model, hyperparameters, features, seed, or stopping point.
- Use nested cross-validation or a single untouched test set to get that data.
- Keep all fitted steps inside the pipeline that the search wraps.
Exercise
A teammate runs GridSearchCV with 200 parameter combinations on 150 rows, then reports search.best_score_ of 0.91 as the expected production accuracy. Explain why this number is likely too high, and describe two ways to get an honest estimate.
Show answer
best_score_ is the maximum over 200 noisy cross-validation scores, so it is biased upward. With only 150 rows the noise in each score is large, and the selection step exploits it. The rows used to score the winner also helped choose it. Two honest options: (1) nested cross-validation, with cross_val_score(GridSearchCV(...), X, y, cv=outer), which scores each inner-search winner on outer rows that were not used in the search; (2) set aside a test set before tuning, run the search only on the remaining rows, and evaluate the refit model once on the test set.
Exercise
In the nested loop cross_val_score(GridSearchCV(SVC(), grid, cv=3), X, y, cv=5), how many times is an SVC fitted if grid has 4 candidates, and what does the mean of the 5 scores estimate?
Show answer
Each outer fold runs 4 candidates × 3 inner splits = 12 fits, plus 1 refit on the outer training rows, which is 13 fits. Over 5 outer folds that is 65 fits. The mean estimates the performance of the whole procedure (tuning with this grid, then fitting the winner), not of one specific set of hyperparameters.