Sub topic 13
Evaluating a pipeline with cross-validation
This chapter assumes you can build a Pipeline, call fit and predict, and use train_test_split. It also assumes you know why fitting a scaler on test data is data leakage.
Why one split is not enough
A single train_test_split gives you one score. That score depends on which rows landed in the test set. A different random seed can give a noticeably different number, especially on small datasets such as Iris with 150 rows.
Cross-validation repeats the split several times. It reports one score per split, so you can see both the average and the spread.
How k-fold cross-validation works
In 5-fold cross-validation, the data is cut into five parts called folds. Each fold is used once as the validation set. The other four folds are used for training.
Passing the whole pipeline
cross_val_score takes an estimator, X, y, and the number of folds cv. For each round it clones the estimator, fits it on the training folds, and scores it on the validation fold. It returns an array with one score per fold.
If you pass a Pipeline, every step is refit inside each round. The scaler learns its mean and variance from the training folds only. The validation fold never influences preprocessing.
from sklearn.datasets import load_iris
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import cross_val_score
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
X, y = load_iris(return_X_y=True)
pipe = make_pipeline(StandardScaler(), LogisticRegression(max_iter=200))
scores = cross_val_score(pipe, X, y, cv=5)
print(scores)
print(scores.mean())
print(scores.std())Report the mean together with the standard deviation. A mean of 0.97 with a standard deviation of 0.02 is a more honest summary than 0.97 alone.
The leaky alternative
The common mistake is to scale all of X first and then cross-validate only the model:
from sklearn.datasets import load_iris
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import cross_val_score
from sklearn.preprocessing import StandardScaler
X, y = load_iris(return_X_y=True)
X_scaled = StandardScaler().fit_transform(X) # sees every row
scores = cross_val_score(LogisticRegression(max_iter=200), X_scaled, y, cv=5)
print(scores.mean())The scaler has already seen the validation rows when it computed its statistics. With a simple scaler the effect is small. With feature selection or target-aware encoders, it can inflate scores badly. Putting the preprocessing inside the pipeline removes the problem.
Choosing folds and metrics
For classifiers, an integer cv uses stratified folds, which keep class proportions similar in every fold. For regressors, it uses plain KFold. If your rows are ordered, for example by class or by time, plain folds can mislead. Pass a splitter explicitly:
from sklearn.model_selection import StratifiedKFold
cv = StratifiedKFold(n_splits=5, shuffle=True, random_state=0)Then use cross_val_score(pipe, X, y, cv=cv). The scoring argument changes the metric. For example, scoring="f1_macro" replaces the default accuracy. For time-ordered data, use TimeSeriesSplit instead.
| Argument | Purpose | Example |
|---|---|---|
| `cv` | Number of folds or a splitter object | `cv=5` |
| `scoring` | Metric used on each validation fold | `scoring="f1_macro"` |
| `n_jobs` | Run folds in parallel | `n_jobs=-1` |
What cross-validation does not give you
cross_val_score does not return a fitted model. The estimators it fits are discarded. To get a final model, call pipe.fit(X, y) on the data you want to train on. Keep a final test set out of all tuning, and use it once at the end.
Exercise
You scale X with StandardScaler().fit_transform(X) and then call cross_val_score(LogisticRegression(), X_scaled, y, cv=5). What is wrong, and how do you fix it?
Show answer
The scaler computed its mean and variance from all rows, including those in each validation fold, so information leaks into training. Fix it by building make_pipeline(StandardScaler(), LogisticRegression()) and passing that pipeline with the raw X to cross_val_score. The scaler is then refit on the training folds in every round.
Exercise
cross_val_score(pipe, X, y, cv=5) returns [0.93, 1.0, 0.97, 0.9, 1.0]. Which two numbers should you report, and why?
Show answer
Report the mean (0.96) and the standard deviation (about 0.04). The mean estimates typical performance and the standard deviation shows how much the score changes between folds.