Sub topic 6
Cross-validating the whole workflow
What this chapter assumes
You should know how to split data with train_test_split, fit an estimator with fit and predict, and build a Pipeline or make_pipeline object. You should also know what a ColumnTransformer does. This chapter covers what happens when you hand a pipeline to the cross-validation tools, why that is more trustworthy than preprocessing by hand, and which mistakes still get through.
The problem cross-validation has with preprocessing
Cross-validation estimates how well a model will do on data it has not seen. It splits the training data into folds, fits on some folds, and scores on the held-out fold. That estimate is only honest if the held-out fold plays no part in fitting. Preprocessing is part of fitting. A scaler learns a mean and a standard deviation, an imputer learns a median, and a feature selector learns which columns correlate with the target.
If you run those steps on the whole dataset first and then cross-validate only the model, every validation fold has already influenced the preprocessing. This is data leakage. With mild steps such as scaling, the score is slightly optimistic. With steps that look at the target, it can be wildly optimistic.
The next example makes this concrete. The features and labels are pure noise, so no honest method can beat chance, which is about 0.5 accuracy.
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.RandomState(0)
X = rng.randn(100, 2000)
y = rng.randint(0, 2, size=100)
# Leaky: the 20 "best" columns are chosen using all 100 labels.
X_selected = SelectKBest(f_classif, k=20).fit_transform(X, y)
leaky = cross_val_score(LogisticRegression(max_iter=1000), X_selected, y, cv=5)
# Honest: selection is refit inside each training split.
pipe = make_pipeline(SelectKBest(f_classif, k=20), LogisticRegression(max_iter=1000))
honest = cross_val_score(pipe, X, y, cv=5)
print("leaky one-shot selection:", leaky.mean())
print("selection inside pipeline:", honest.mean())The leaky score typically lands far above 0.5. With 2000 noise columns, some correlate with the labels by luck, and choosing them using every label lets the validation folds "vote" on which columns to keep. The pipeline score stays near chance, which is the right answer for noise.
What cross_val_score does with a pipeline
A pipeline is a single estimator, so cross_val_score treats it like any other model. For each fold it does the following:
- Clones the pipeline, so every step starts unfitted.
- Calls
fiton the training folds. Each transformer runsfit_transformand passes its output to the next step. The final estimator then fits. - Calls
predictorscoreon the validation fold. Each transformer runs onlytransform, using the statistics it learned from the training folds. - Records the score and discards the fitted clone.
The validation fold never reaches a fit call. Because the loop repeats for every fold, each fold gets its own scaler with its own mean and standard deviation.
The standard workflow
The usual pattern keeps a final test set apart. You cross-validate on the training portion to compare and tune choices, then touch the test set once.
from sklearn.datasets import load_breast_cancer
from sklearn.exceptions import NotFittedError
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import cross_val_score, train_test_split
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
X, y = load_breast_cancer(return_X_y=True)
X_train, X_test, y_train, y_test = train_test_split(
X, y, stratify=y, random_state=0
)
pipe = make_pipeline(StandardScaler(), LogisticRegression(max_iter=1000))
scores = cross_val_score(pipe, X_train, y_train, cv=5)
print(scores.mean(), scores.std())
# cross_val_score fits clones, so the original pipeline is still unfitted.
try:
pipe.predict(X_test)
except NotFittedError:
print("pipe is not fitted yet")
pipe.fit(X_train, y_train)
print(pipe.score(X_test, y_test))Two details matter here. First, cross_val_score never fits the object you pass in, so you must call fit yourself before predicting. Expecting a fitted model afterwards is a common mistake. Second, stratify=y keeps the class balance equal in the training and test parts, which matters when one class is rare.
Choosing the splitter
An integer cv is a shortcut. For a classifier with binary or multiclass labels, cv=5 means StratifiedKFold(5) without shuffling. For regressors it means plain KFold(5) without shuffling. If your rows are sorted by class, date, or source file, unshuffled folds can be badly unrepresentative. Pass a splitter object when you need control.
| Situation | Splitter | Why |
|---|---|---|
| Classification with imbalanced classes | `StratifiedKFold(shuffle=True, random_state=0)` | Each fold keeps the class ratio |
| Rows sorted in some meaningful order | Any splitter with `shuffle=True` | Avoids folds that are all one kind of row |
| Several rows per patient, user, or device | `GroupKFold` with `groups=` | Keeps one group entirely in one fold |
| Time-ordered data | `TimeSeriesSplit` | Validation always comes after training |
| Small dataset, noisy score | `RepeatedStratifiedKFold` | Averages over several random partitions |
Group and time structure are not something a pipeline can fix. If rows from one patient land in both training and validation folds, the model can memorize patient-specific traits and the score will be inflated even though no preprocessing step leaked. You pass the group labels to the search function, not to the pipeline: cross_val_score(pipe, X, y, cv=GroupKFold(5), groups=patient_ids).
Getting more than one number
cross_val_score returns one metric. cross_validate returns a dictionary with several metrics, timings, and optionally the fitted clones.
from sklearn.datasets import load_breast_cancer
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import StratifiedKFold, cross_validate, train_test_split
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
X, y = load_breast_cancer(return_X_y=True)
X_train, X_test, y_train, y_test = train_test_split(
X, y, stratify=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_train_score=True,
return_estimator=True,
n_jobs=-1,
)
print(sorted(results))
print("test accuracy:", results["test_accuracy"].mean())
print("train accuracy:", results["train_accuracy"].mean())
print("test AUC:", results["test_roc_auc"].mean())
# Each fold fitted its own scaler on its own training rows.
for fold, est in enumerate(results["estimator"]):
print(fold, est[0].mean_[:2])The loop at the end shows the refitting directly. The first two feature means differ slightly from fold to fold, because each scaler saw a different set of training rows. If they were identical, the scaler would have been fitted outside the loop.
Some points about the options:
scoringaccepts a name such as"roc_auc", a list of names, or a dictionary mapping names to scorers. The default is the estimator's ownscoremethod, which is accuracy for classifiers and R squared for regressors.return_train_score=Trueis off by default because it costs extra time. A large gap between train and test scores signals overfitting.return_estimator=Truekeeps the fitted clones, which lets you check what each fold learned.n_jobs=-1runs folds in parallel. Each fold is independent, so this is safe.- The keys are
test_<metric>andtrain_<metric>, plusfit_timeandscore_time.
Reading the result
The mean of the fold scores is your estimate. The standard deviation tells you how sensitive that estimate is to the split. Treat it as a rough guide, not a confidence interval. The training sets of different folds overlap heavily, so the fold scores are correlated and the true uncertainty is larger than the spread suggests. When two candidate pipelines differ by less than a standard deviation, you generally cannot say which is better. Repeated cross-validation over several shuffles gives a steadier comparison.
cross_val_predict and its limits
cross_val_predict returns one out-of-fold prediction per row. Each prediction comes from a model that did not see that row, and the pipeline is refit per fold as before. It is useful for confusion matrices and residual plots.
Two cautions apply. It requires splitters that put every row in exactly one validation set, so ShuffleSplit and similar splitters fail. Also, scoring the pooled predictions with one metric is not the same as averaging per-fold scores, and it hides fold-to-fold variation. Prefer cross_val_score or cross_validate for reporting.
Mistakes that survive the pipeline
Putting everything in a pipeline removes the most common leak, but not all of them.
- Preprocessing outside the pipeline. Calling
df.fillna(df.mean()),pd.get_dummies, or a scaler'sfit_transformon the full dataset before splitting reintroduces the leak. If a step learns anything from the data, it belongs inside the pipeline. - Tuning against the test set. If you look at test performance, change the pipeline, and look again, the test set is now part of model selection. Use cross-validation for choices, and use the test set once at the end.
- Resampling steps. The standard
Pipelineexpects each step to keep the same number of rows. Oversamplers such as SMOTE change the row count and come from the separateimbalanced-learnpackage, which provides its own pipeline class. Oversampling the data before cross-validation duplicates information across folds and inflates scores. - Hidden structure in the rows. Duplicates, repeated subjects, and time order cause leakage that no preprocessing step can detect. Choose the splitter to match how the model will be used.
- Target-aware steps. Feature selection, target encoding, and supervised dimensionality reduction see the labels. They are the steps that leak most, so they must be inside.
- Silent fold failures. By default, a fold that raises an exception gets a score of
nanand a warning. Passerror_score="raise"while developing so the real traceback appears.
Checking that your setup is leak-free
One quick test is to replace the labels with random values and rerun the whole cross-validation. An honest pipeline should score near chance. If it scores well above chance, something is leaking. The selection example earlier in this chapter is this test applied to a pipeline with a deliberately leaky comparison.
Exercise
A colleague scales the full dataset with StandardScaler, then calls crossvalscore(LogisticRegression(), X_scaled, y, cv=5). Explain what leaks and how to fix the code so each fold is evaluated honestly.
Show answer
The scaler computed its mean and standard deviation from all rows, including the rows that later serve as each validation fold. The validation data therefore influenced the transformation applied to the training data. The fix is to build makepipeline(StandardScaler(), LogisticRegression()) and pass the unscaled X to crossval_score. The pipeline then refits the scaler on the training folds of each split and only applies transform to the validation fold.
Exercise
After running scores = crossvalscore(pipe, Xtrain, ytrain, cv=5), you call pipe.predict(X_test) and get a NotFittedError. Why does this happen, and what should you do before predicting? Also name which splitter you would choose if several rows in the data belong to the same patient.
Show answer
crossvalscore fits clones of the pipeline for each fold and discards them, so the pipe object you passed in is never fitted. Call pipe.fit(Xtrain, ytrain) before pipe.predict(X_test). For repeated patients, use GroupKFold and pass the patient identifiers through the groups argument, so that all rows from one patient fall in the same fold.