Sub topic 13
Cross-validation for reliable estimates
This chapter assumes you can split data with train_test_split, know what a pipeline is, and have seen overfitting. It covers how to get a score you can trust without touching the test set.
Why one split is not enough
A single validation split gives one number. That number depends on which rows landed in the validation set. With a small dataset, two different random seeds can produce scores that differ by several points. You cannot tell whether a model is better or just luckier.
Cross-validation (CV) repeats the train-and-validate step several times on different parts of the training data and averages the results. You get a mean score and a sense of its spread.
How k-fold works
In k-fold CV, the training data is cut into k equal parts called folds. Each fold takes one turn as the validation set while the other k-1 folds are used for fitting. After k rounds, every row has been used for validation exactly once.
Running it correctly
Pass the whole pipeline to cross_val_score, not pre-transformed data. The pipeline then refits the scaler on each training fold. If you scale first and cross-validate afterward, the scaler has seen the validation fold, which is data leakage.
from sklearn.datasets import load_breast_cancer
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import StratifiedKFold, cross_val_score, train_test_split
from sklearn.pipeline import 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, test_size=0.2, stratify=y, random_state=42
)
model = Pipeline([
("scale", StandardScaler()),
("clf", LogisticRegression(max_iter=1000)),
])
cv = StratifiedKFold(n_splits=5, shuffle=True, random_state=42)
scores = cross_val_score(model, X_train, y_train, cv=cv, scoring="f1")
print("Fold scores:", scores.round(3))
print(f"Mean F1: {scores.mean():.3f} +/- {scores.std():.3f}")Read the standard deviation as well as the mean. A high mean with a large spread means the model is unstable across subsets of the data.
Choosing the splitter
| Situation | Splitter |
|---|---|
| Classification, especially imbalanced classes | `StratifiedKFold` |
| Regression or balanced data | `KFold` with `shuffle=True` |
| Several rows per customer, patient or device | `GroupKFold` |
| Rows ordered in time | `TimeSeriesSplit` |
Common errors
- Fitting preprocessing outside the pipeline, which leaks validation information into each fold.
- Using the test set inside CV. CV belongs to the training data only.
- Comparing models using different folds. Fix
random_stateor reuse the samecvobject. - Treating a small difference in mean score as meaningful when it is smaller than the standard deviation.
- Using a large k on a slow model. Five or ten folds is usually enough, and cost grows linearly with k.
Using CV for diagnosis
Use cross_validate with return_train_score=True to compare training and validation scores per fold. A large gap points to overfitting. Low scores on both point to underfitting. This feeds directly into tuning, where CV chooses hyperparameters.
Exercise
You scale all features with StandardScaler, then run crossvalscore on the scaled array with a logistic regression. Why can the result be too optimistic, and how do you fix it?
Show answer
The scaler computed its mean and variance using every row, including the rows that later serve as the validation fold in each round, so information leaks from validation into training. Put the scaler and the model in one Pipeline and pass the pipeline to crossvalscore, so the scaler is refit on only the training folds in each round.
Exercise
A dataset has 10 rows per patient, and you want to know how the model performs on new patients. Which splitter should you use, and why?
Show answer
Use GroupKFold with patient IDs as groups. It keeps all rows from one patient in the same fold, so the validation fold contains only unseen patients, matching real use.