Sub topic 6
Cross-validating the whole workflow
This chapter assumes you can build a Pipeline or make_pipeline object, and that you know what a train/test split and fit/predict do. You will see how cross-validation treats a pipeline as one estimator, and why that keeps validation scores honest.
What cross-validation does to a pipeline
Cross-validation splits the training data into k folds. It trains on k − 1 folds and scores on the held-out fold, then repeats until every fold has served as the held-out part once.
A pipeline is itself an estimator, so you can pass it to cross_val_score unchanged. For each split, scikit-learn clones the whole pipeline and calls fit on the training folds. That fit refits every step, including the scaler. The validation fold only goes through transform and predict.
Scoring a pipeline
from sklearn.datasets import load_breast_cancer
from sklearn.model_selection import train_test_split, cross_val_score
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.linear_model import LogisticRegression
X, y = load_breast_cancer(return_X_y=True)
X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=0)
pipe = make_pipeline(StandardScaler(), LogisticRegression(max_iter=1000))
# The scaler is refit on the training part of each fold, so no information leaks from the validation part.
scores = cross_val_score(pipe, X_train, y_train, cv=5)
print(scores.mean())
pipe.fit(X_train, y_train)
print(pipe.score(X_test, y_test))Notice the order of work:
- Cross-validation runs on
X_trainonly. It guides model choices. - The final
fiton all ofX_trainproduces the model you ship. - The test set is scored once, at the end.
The leaky alternative
The common mistake is to scale first and cross-validate afterwards:
# Wrong: the scaler has already seen every row, including future validation rows.
X_scaled = StandardScaler().fit_transform(X_train)
scores = cross_val_score(LogisticRegression(max_iter=1000), X_scaled, y_train, cv=5)Each validation fold now influenced the mean and standard deviation used to scale it. With plain scaling the score gap is usually small. The problem grows with steps that learn more from the data, such as feature selection or target encoding. Those can inflate scores badly. Putting every fitted step inside the pipeline removes the whole class of error.
More control with cross_validate
cross_val_score returns one metric. cross_validate returns a dictionary, supports several metrics, and can keep the fitted pipeline from each fold.
from sklearn.datasets import load_breast_cancer
from sklearn.model_selection import train_test_split, cross_validate, StratifiedKFold
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.linear_model import LogisticRegression
X, y = load_breast_cancer(return_X_y=True)
X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=0)
pipe = make_pipeline(StandardScaler(), LogisticRegression(max_iter=1000))
cv = StratifiedKFold(n_splits=5, shuffle=True, random_state=0)
results = cross_validate(
pipe, X_train, y_train,
cv=cv,
scoring=["accuracy", "roc_auc"],
return_estimator=True,
)
print(results["test_accuracy"].mean())
print(results["test_roc_auc"].mean())
# Each fold fitted its own scaler on different training rows.
for fold_pipe in results["estimator"]:
print(fold_pipe.named_steps["standardscaler"].mean_[:2])The printed scaler means differ slightly between folds. That difference shows each fold learned its statistics only from its own training rows.
| Function | Returns | Use it when |
|---|---|---|
| `cross_val_score` | Array of one metric per fold | You want a quick single number |
| `cross_validate` | Dictionary with scores, fit times, optional estimators | You need several metrics or timing |
| `cross_val_predict` | Out-of-fold predictions | You want to inspect errors, not report a score |
Common errors
- Reporting the cross-validation mean as the final result. It is a development estimate. Report the score on the untouched test set.
- Cross-validating on the full dataset and then splitting. The test rows have then influenced model choices.
- Ignoring the splitter. For classifiers with an integer
cv, scikit-learn uses stratified folds without shuffling. If your rows are ordered, for example by date or class, pass aStratifiedKFoldwithshuffle=True. For time series, useTimeSeriesSplitinstead. - Reading a fold's spread as noise. A large standard deviation across folds means the mean is unreliable. Report both.
Exercise
You call StandardScaler().fit_transform(X_train) and then run cross_val_score on the scaled array with a plain classifier. Why is the score biased, and what is the fix?
Show answer
The scaler computed its mean and standard deviation from all rows of X_train, including the rows that later serve as validation folds, so validation data influenced preprocessing. The fix is to put the scaler and the classifier in one pipeline and pass that pipeline to cross_val_score. The scaler is then refit on the training folds of each split.
Exercise
What does return_estimator=True in cross_validate give you, and what can you check with it?
Show answer
It returns the fitted pipeline from each fold under the estimator key. You can inspect each fold's steps, for example named_steps["standardscaler"].mean_, to confirm each fold learned its statistics from different training rows.