Sub topic 13
Evaluating a pipeline with cross-validation
A single train/test split gives you one accuracy number, and that number depends on which rows landed in the test set. Cross-validation repeats the split several times and averages the results. This chapter shows how to run it on a Pipeline, how to read the output, and where it can mislead you.
This chapter assumes you know train_test_split, the fit/predict/score methods, and how Pipeline chains a preprocessing step and a model. Familiarity with NumPy arrays is also assumed.
Why one split is not enough
Suppose you hold out 25% of 150 iris samples. The test set has 38 rows, so one misclassified flower changes accuracy by about 2.6 percentage points. A different random_state can give a noticeably different score. You can't tell whether a model with 0.95 accuracy is better than one with 0.93, or whether you were just lucky.
Cross-validation addresses this by using every row for both training and evaluation, though never in the same round. The most common form is k-fold:
- Split the data into k folds of roughly equal size.
- For each fold, train on the other k-1 folds and score on the held-out fold.
- Collect the k scores.
You get k estimates instead of one, so you can report a mean and a spread.
Running cross_val_score on a pipeline
The function cross_val_score takes an unfitted estimator, the full X and y, and a cv setting. It returns one score per fold.
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())Internally, cross_val_score calls clone on the estimator for each fold. Each clone is unfitted and has the same constructor settings (see the earlier chapter on get_params and clone). That has two consequences:
- Your original
pipeobject is never fitted by this call. Callingpipe.predictafterwards raisesNotFittedError. - Each fold gets a pipeline whose
StandardScalerlearned its mean and variance from that fold's training rows only.
The second point is why you pass the whole pipeline instead of preprocessed data. The scaler's fit runs inside every round, on training rows only.
Seeing the leak that pipelines prevent
The leakage chapter described what happens when you fit a transformer on all the data. Cross-validation makes the problem worse, because the leak reaches every fold. Feature selection shows this most clearly. The next example uses pure noise, so no model should score much above 0.5.
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.normal(size=(100, 2000))
y = rng.randint(0, 2, size=100)
# Wrong: the selector sees every label before the folds are made.
X_selected = SelectKBest(f_classif, k=20).fit_transform(X, y)
leaky = cross_val_score(LogisticRegression(), X_selected, y, cv=5).mean()
# Right: selection is refitted inside each training fold.
pipe = make_pipeline(SelectKBest(f_classif, k=20), LogisticRegression())
honest = cross_val_score(pipe, X, y, cv=5).mean()
print(f"leaky: {leaky:.2f}, honest: {honest:.2f}")The leaky score comes out well above 0.5, and the honest score stays near 0.5. Exact values depend on your library version. The selector in the leaky version picked the 20 noise columns that happened to correlate with y across all 100 rows, including the rows that later became validation folds. The model then looks skilled on data it has indirectly seen. With scaling the effect is usually small, but with supervised steps such as feature selection it can be large.
Choosing the splitting strategy
The cv argument accepts an integer, a splitter object, or an iterable of index pairs. When you pass an integer, scikit-learn picks the splitter for you.
| `cv` value | Splitter used | Notes |
|---|---|---|
| `5` with a classifier and a class-label `y` | `StratifiedKFold(5)` | Keeps class proportions in each fold. No shuffling. |
| `5` with a regressor | `KFold(5)` | No shuffling. |
| `StratifiedKFold(5, shuffle=True, random_state=0)` | As given | Use when row order carries meaning. |
| `GroupKFold(5)` | Groups never split across folds | Needs the `groups` argument. |
| `TimeSeriesSplit(5)` | Training always precedes validation | For ordered data. |
The default does not shuffle. If your file is sorted, for example by date, customer, or label, the folds are contiguous slices of that order. For ordinary tabular data, pass an explicit splitter with shuffle=True and a fixed random_state, so results are repeatable:
from sklearn.datasets import load_iris
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import StratifiedKFold, 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))
cv = StratifiedKFold(n_splits=5, shuffle=True, random_state=0)
scores = cross_val_score(pipe, X, y, cv=cv)
print(f"{scores.mean():.3f} +/- {scores.std():.3f}")Do not shuffle when rows are not independent. If several rows come from the same patient, customer, or sensor, shuffled folds put the same entity in both training and validation, which inflates the score. Use GroupKFold and pass groups= to cross_val_score. For time-ordered data, use TimeSeriesSplit, because shuffling would let the model train on the future.
Choosing the metric
By default cross_val_score uses the estimator's own score method. For classifiers that is accuracy, and for regressors it is R². Use the scoring argument to choose another metric by name:
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))
f1 = cross_val_score(pipe, X, y, cv=5, scoring="f1_macro")
print(f1.mean())All scorers follow the rule that higher is better. Loss metrics are therefore negated and carry a neg_ prefix. With scoring="neg_mean_squared_error", a result of -4.0 means a mean squared error of 4.0, and a score closer to zero is better. A common bug is taking the -4.0 for a real error value, or reading a "bigger" negative number as an improvement.
Several metrics and timing with cross_validate
cross_val_score returns only one array. cross_validate returns a dictionary and accepts several metrics at once:
from sklearn.datasets import load_iris
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import StratifiedKFold, cross_validate
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))
cv = StratifiedKFold(n_splits=5, shuffle=True, random_state=0)
results = cross_validate(
pipe, X, y, cv=cv,
scoring=["accuracy", "f1_macro"],
return_train_score=True,
)
for key in sorted(results):
print(key, results[key].round(3))The keys are fit_time, score_time, test_accuracy, test_f1_macro, train_accuracy, and train_f1_macro. Setting return_train_score=True adds the train_ entries, which are useful for diagnosis. A high training score with a much lower test score suggests overfitting. Low scores on both suggest underfitting.
Reading the results
- Report the mean and the standard deviation. A mean of 0.96 with a standard deviation of 0.02 is a different claim from 0.96 with 0.08.
- Treat differences smaller than the spread with suspicion. The folds share training data, so the k scores are not independent, and the standard deviation understates the true uncertainty.
- Compare models on identical folds. Pass the same splitter object, with a fixed
random_state, to every model. - Remember that no fitted model comes out of the call. To get a model for predictions, call
pipe.fit(X, y)yourself on the training data afterwards.
Common errors
- Passing
X_train_scaledinstead of the pipeline. The scaler has already seen all rows, so the fold scores are optimistic. - Expecting
pipeto be fitted aftercross_val_score. It is not, because the function works on clones. - Relying on default folds with sorted data and a regressor, since
KFolddoes not shuffle. - Forgetting
groupswhen usingGroupKFold, which raises an error. - Reading
neg_scores as errors with the wrong sign. - Setting
n_jobs=-1for a pipeline that is already fast. Process start-up can cost more than it saves. It helps when each fit takes seconds or more.
Exercise
A colleague scales the full dataset with StandardScaler().fittransform(X), then runs crossvalscore(LogisticRegression(), Xscaled, y, cv=5). What is wrong, and how do you fix it?
Show answer
The scaler learned the mean and variance from every row, including the rows that become validation folds in each round, so information from the validation data leaks into preprocessing. Fix it by putting the scaler and the model in one pipeline, for example makepipeline(StandardScaler(), LogisticRegression()), and passing the raw X to crossval_score. The scaler is then refitted on the training folds of each round.
Exercise
You run crossvalscore(reg, X, y, cv=5, scoring="negmeansquared_error") and get a mean of -12.5 for model A and -9.0 for model B. Which model is better, and what is each model's mean squared error?
Show answer
Model B is better. Scorers are defined so that higher is better, so -9.0 is greater than -12.5. The mean squared errors are 12.5 for A and 9.0 for B, the scores with the sign flipped.