Sub topic 10
Avoiding leakage and optimistic scores with pipelines and nested cross-validation
This chapter assumes you can train and score a scikit-learn model, you know what a train/validation/test split is, and you have run GridSearchCV or RandomizedSearchCV at least once. It covers two ways a tuning score can mislead you, and the tools that prevent each one.
Two sources of optimism
A tuning run can report a score that is higher than what the model will achieve on new data. There are two separate causes.
- Data leakage. Information from the validation data influences training. Example: fitting a scaler on the whole dataset before cross-validation, so every fold's scaler has already seen that fold's validation rows.
- Selection bias. You pick the best of many candidates by their cross-validation score, then report that same score. The maximum of many noisy estimates is biased upward, even when no leakage exists.
Pipelines fix the first cause. Nested cross-validation measures and removes the second.
Leakage through preprocessing
Any step that learns something from data is part of the model. Scalers learn means and variances. Imputers learn medians. Feature selectors learn which columns matter. Target encoders learn category means. If these steps are fitted on all rows before you split, validation rows have influenced the model that is later scored on them.
Here is the leaky pattern:
from sklearn.datasets import load_breast_cancer
from sklearn.model_selection import cross_val_score
from sklearn.preprocessing import StandardScaler
from sklearn.svm import SVC
X, y = load_breast_cancer(return_X_y=True)
X_scaled = StandardScaler().fit_transform(X) # fitted on every row
scores = cross_val_score(SVC(), X_scaled, y, cv=5)
print("Leaky CV accuracy:", scores.mean())On a dataset like this one the difference is small, because scaling statistics are stable. Leakage becomes severe with supervised steps, such as selecting the top features by correlation with the label. With many features and few rows, that kind of leak can produce high scores on data with no real signal.
The fix: put preprocessing inside a pipeline
A Pipeline bundles preprocessing and the estimator into one object. When cross-validation calls fit on a training fold, every step is fitted on that fold only. When it scores the validation fold, the steps only call transform.
from sklearn.datasets import load_breast_cancer
from sklearn.model_selection import 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())
scores = cross_val_score(pipe, X, y, cv=5)
print("Pipeline CV accuracy:", scores.mean())The same rule applies when the pipeline is passed to GridSearchCV. Preprocessing settings can be tuned too, using step names as prefixes, such as svc__C or standardscaler__with_mean.
A demonstration with pure noise
A strong way to see leakage is to use data that has no signal at all. Any accuracy well above 50% is then an artifact.
import numpy as np
from sklearn.feature_selection import SelectKBest, f_classif
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import cross_val_score
from sklearn.pipeline import make_pipeline
rng = np.random.default_rng(0)
X = rng.normal(size=(60, 2000))
y = rng.integers(0, 2, size=60)
# Leaky: select features using all labels, then cross-validate
X_sel = SelectKBest(f_classif, k=20).fit_transform(X, y)
leaky = cross_val_score(LogisticRegression(max_iter=1000), X_sel, y, cv=5)
# Correct: selection happens inside each training fold
pipe = make_pipeline(
SelectKBest(f_classif, k=20), LogisticRegression(max_iter=1000)
)
honest = cross_val_score(pipe, X, y, cv=5)
print("Leaky:", leaky.mean())
print("Honest:", honest.mean())The leaky score is typically far above 0.5. The honest score stays near 0.5, which is the truth for random labels. The exact numbers depend on the seed, but the gap is the point.
Selection bias in the tuning score
Suppose you run a grid of 100 settings, and each has a true accuracy of 90%. Cross-validation estimates are noisy, so some settings score 92% and others 88% by chance. best_score_ reports the highest, so it lands above 90% even though no setting is better than any other. The more settings you try, and the noisier the folds, the larger the bias.
The value search.best_score_ was used to choose the winner. It is therefore not an unbiased estimate of how that winner will perform later.
There are two ways to get an honest number:
- Hold out a test set. Tune on the training portion, then score the test set once, as in the grid search example earlier in this tutorial. This works well when you have plenty of data.
- Nested cross-validation. Use it when data is scarce and a single test split would be too small or too variable to trust.
Nested cross-validation
Nested cross-validation has two loops.
- The inner loop performs the tuning. For one outer training set, it cross-validates every candidate setting and picks the best.
- The outer loop evaluates. It splits the data into outer training and outer test folds. Each outer test fold is scored by a model that was tuned using only the corresponding outer training fold.
The outer scores never influenced model selection, so they estimate how well the whole procedure performs: preprocessing, tuning, and final fit together.
Running it in scikit-learn
A GridSearchCV object is itself an estimator. You can pass it to cross_val_score, which supplies the outer loop.
from sklearn.datasets import load_breast_cancer
from sklearn.model_selection import GridSearchCV, KFold, 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": [0.001, 0.01, 0.1]}
inner_cv = KFold(n_splits=3, shuffle=True, random_state=1)
outer_cv = KFold(n_splits=5, shuffle=True, random_state=2)
inner = GridSearchCV(pipe, param_grid, cv=inner_cv)
outer_scores = cross_val_score(inner, X, y, cv=outer_cv)
print(outer_scores)
print(outer_scores.mean(), outer_scores.std())Using different random states for the inner and outer splitters is a good habit. Using separate splitter objects also makes the structure easy to read. For classification, StratifiedKFold is usually preferable to KFold. Note that when you pass an integer to cv for a classifier, scikit-learn already uses stratified folds.
What the result means
Nested cross-validation does not produce a final model. It produces an estimate of how a procedure performs. Each outer fold may have chosen different hyperparameters, and that is expected.
To get a model for deployment, run the search once on all available data (or on the training portion if you hold out a test set), and use the refit best_estimator_. The nested score is the figure you report for how well that procedure should generalize.
You can also record which setting each outer fold chose. Use cross_validate with return_estimator=True:
from sklearn.datasets import load_breast_cancer
from sklearn.model_selection import GridSearchCV, cross_validate
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": [0.001, 0.01, 0.1]}
inner = GridSearchCV(pipe, param_grid, cv=3)
result = cross_validate(inner, X, y, cv=5, return_estimator=True)
for fold, est in enumerate(result["estimator"]):
print(fold, est.best_params_)If the chosen settings differ widely across folds, the score surface is flat or noisy. Several settings perform about equally well, so the exact choice matters less.
Cost
Nested cross-validation multiplies the work. With 5 outer folds, 3 inner folds, and 9 candidates, scikit-learn fits 5 × (9 × 3 + 1) = 140 models. Candidate counts and fold counts multiply quickly, so use n_jobs and keep the outer loop modest (5 folds is common). Random search shrinks the candidate count if the grid is too large.
Other leakage routes
Pipelines handle preprocessing. Some leaks need separate care.
- Duplicate or near-duplicate rows. If copies of one record land in both training and validation folds, the model memorizes them. Deduplicate before splitting.
- Grouped data. Several rows from one patient, user, or device are correlated. Use
GroupKFoldand passgroups=so that one group never spans training and validation. - Time series. Random folds let the model train on the future and predict the past. Use
TimeSeriesSplit, and keep any feature built from rolling windows computed only from earlier rows. - Target-derived features. A column that is computed from the label, or recorded after the outcome is known, will inflate every score.
- Repeated peeking at the test set. If you evaluate on the test set, adjust the setup, and evaluate again, the test set has become a validation set. Its score is no longer an honest estimate.
Common errors
| Mistake | Effect | Fix |
|---|---|---|
| Fitting a scaler or imputer on all data before splitting | Mildly optimistic scores | Put it in a `Pipeline` |
| Supervised feature selection outside the CV loop | Severely optimistic scores | Put the selector in the pipeline |
| Reporting `best_score_` as the final performance | Optimistic by selection bias | Use a test set or nested CV |
| Using the same fold splits for inner and outer loops | Correlated estimates | Use separate splitters with different seeds |
| Treating nested CV scores as a model | No model is produced | Refit the search on all training data |
| Ignoring groups or time order | Optimistic scores | Use `GroupKFold` or `TimeSeriesSplit` |
Exercise
You run a GridSearchCV with 50 candidates and 5-fold cross-validation on a dataset of 300 rows, and best_score_ is 0.91. A colleague wants to publish 0.91 as the expected accuracy. Give two reasons the figure may be optimistic, and name one method that gives a more honest estimate.
Show answer
First, selection bias: the best of 50 noisy cross-validation scores is biased upward, because the winner was chosen for having a high score. Second, possible leakage: if any preprocessing step (scaling, imputing, feature selection) was fitted on the full dataset before cross-validation instead of inside a pipeline, the validation folds influenced training. A more honest estimate comes from nested cross-validation, where an inner GridSearchCV picks the setting and an outer loop scores folds that played no part in the choice. A held-out test set scored once also works, though with only 300 rows it would be small and noisy.
Exercise
With 4 outer folds, 3 inner folds, and 6 candidate settings, how many model fits does nested cross-validation perform, assuming each inner search refits the best model on its whole outer training set?
Show answer
Each outer fold runs 6 candidates × 3 inner folds = 18 fits for the search, plus 1 refit of the best setting, which is 19 fits. Over 4 outer folds that is 4 × 19 = 76 fits.