Sub topic 10
Avoiding leakage and optimistic scores with pipelines and nested cross-validation
This chapter assumes you know how to run cross_val_score and GridSearchCV in scikit-learn, and that you understand train, validation, and test splits. Two mistakes make tuning scores look better than they are: leakage and reusing tuning data for evaluation.
Leakage through preprocessing
Data leakage happens when information from outside the training data influences the model. A common case is fitting a scaler on the whole dataset before cross-validation. The scaler's mean and standard deviation then include the validation rows of every fold, so each fold's score is slightly too good.
The fix is to put preprocessing and the model in one Pipeline. When you pass a pipeline to GridSearchCV or cross_val_score, scikit-learn refits every step on the training part of each fold only.
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.svm import SVC
pipe = make_pipeline(StandardScaler(), SVC())Parameters of pipeline steps are addressed as stepname__param, for example svc__C. The earlier chapters used this naming in the grid and random search examples.
Optimistic scores from reusing tuning data
Even with a pipeline, there is a second problem. best_score_ is the highest of many cross-validation scores. Picking the maximum of noisy numbers biases it upward. The more settings you try, the larger the bias.
A held-out test set avoids this, but it gives you one estimate from one split. With small datasets that estimate can be noisy. Nested cross-validation gives a steadier estimate by using two loops:
- The inner loop picks hyperparameters, using only the outer training data.
- The outer loop scores the chosen model on rows the inner loop never saw.
Running nested cross-validation
An inner GridSearchCV is itself an estimator, so you can pass it to cross_val_score.
from sklearn.datasets import load_breast_cancer
from sklearn.model_selection import GridSearchCV, 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 = GridSearchCV(pipe, param_grid, cv=3)
outer_scores = cross_val_score(inner, X, y, cv=5)
print(outer_scores.mean(), outer_scores.std())The mean estimates how well "tune, then fit" performs on new data. The standard deviation shows how much that estimate varies between folds.
Each outer fold may choose different settings. That is expected. Nested cross-validation evaluates the procedure, not one specific model.
What to do with the result
Nested cross-validation does not produce a final model. After you have the estimate, run the tuning search once on all your training data and fit the final model with the winning settings. Report the nested score as your expected performance.
It is also costly. With 3 inner folds, 9 grid points, and 5 outer folds, the model is trained 5 × (9 × 3 + 1) = 140 times.
| Approach | Leakage-safe | Unbiased estimate | Cost |
|---|---|---|---|
| Scale all data, then cross-validate | No | No | Low |
| Pipeline inside `GridSearchCV`, read `best_score_` | Yes | No, optimistic | Medium |
| Pipeline with a held-out test set | Yes | Yes, one noisy split | Medium |
| Nested cross-validation | Yes | Yes, steadier | High |
Exercise
You fit StandardScaler on all rows, then run GridSearchCV with an SVC. Name the leak and give the fix.
Show answer
The scaler's mean and standard deviation use the validation rows of every fold. Put the scaler and SVC in one pipeline and pass the pipeline to GridSearchCV, so scaling is refit on each fold's training part only.
Exercise
Why is best_score_ from a grid search an optimistic estimate of test performance?
Show answer
It is the maximum over many noisy cross-validation scores, and the same data was used to choose the settings and to score them. Nested cross-validation or a separate test set avoids this.