Sub topic 13
Cross-validation for reliable estimates
This chapter assumes you can split data with train_test_split, you know what a scikit-learn pipeline is, and you have met overfitting and metrics such as F1. Here you will learn why one validation split gives a noisy score, how k-fold cross-validation fixes that, and which mistakes make cross-validated scores wrong.
Why one split is not enough
A single train/validation split gives one number. That number depends on which rows landed in the validation set. With a small dataset, a lucky or unlucky split can move the score by several points. You cannot tell whether a difference between two models is real or just a product of the split.
Cross-validation repeats the split several times and averages the results. Every row is used for validation exactly once, and the spread of the scores shows how stable the estimate is.
How k-fold cross-validation works
In k-fold cross-validation, you divide the training data into k equal parts called folds. You then run k rounds. In each round, one fold is held out for validation and the model trains on the other k-1 folds. You end up with k scores.
The mean is your estimate of performance. The standard deviation tells you how much it moves from fold to fold. A mean of 0.95 with a standard deviation of 0.01 is a more trustworthy result than 0.95 with a standard deviation of 0.08.
Common choices are k = 5 or k = 10. A larger k means each model trains on more data, so the estimate is less pessimistic, but it costs more fits. Five folds means five model fits. Ten means ten.
Cross-validation on the training set only
Cross-validation belongs inside the training data. The test set stays untouched until the final evaluation. If you cross-validate on the whole dataset and then tune based on the results, the test set has influenced your choices and can no longer give an honest final score.
The workflow is:
- Split off the test set and set it aside.
- Run cross-validation on the training set to compare models and settings.
- Pick the final configuration and refit it on the full training set.
- Score once on the test set.
Running it with a pipeline
Pass the whole pipeline to cross_val_score, not pre-transformed data. Then scikit-learn refits every step, including the scaler, on each round's training folds only. This prevents leakage from the validation fold.
from sklearn.datasets import load_breast_cancer
from sklearn.model_selection import train_test_split, cross_val_score
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.linear_model import LogisticRegression
X, y = load_breast_cancer(return_X_y=True, as_frame=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)),
])
scores = cross_val_score(model, X_train, y_train, cv=5, scoring="f1")
print("fold scores:", scores.round(3))
print(f"mean = {scores.mean():.3f}, std = {scores.std():.3f}")The output has five fold scores, then their mean and standard deviation. Exact values depend on your scikit-learn version, but the scores should be high and close together on this dataset.
Stratified folds for classification
With a classification target, a plain random split can produce folds with very different class proportions. If only 5% of rows are positive, one fold might contain almost none. Stratified k-fold keeps the class proportions in each fold close to those of the full training set.
When you pass an integer such as cv=5 with a classifier, scikit-learn already uses stratified k-fold. For a regressor, it uses ordinary k-fold. You can also pass a splitter explicitly, which lets you control shuffling and the random seed.
from sklearn.datasets import load_breast_cancer
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_breast_cancer(return_X_y=True)
cv = StratifiedKFold(n_splits=5, shuffle=True, random_state=0)
model = make_pipeline(StandardScaler(), LogisticRegression(max_iter=1000))
scores = cross_val_score(model, X, y, cv=cv, scoring="roc_auc")
print(scores.round(3), scores.mean().round(3))Note that StratifiedKFold without shuffle=True keeps the original row order. If the file is sorted in some way, such as by date or by class, shuffling matters.
Choosing the right splitter
The default splitter assumes rows are independent. When that assumption fails, the scores become too optimistic. Pick a splitter that matches how the data was produced.
| Situation | Splitter | Reason |
|---|---|---|
| Classification, independent rows | `StratifiedKFold` | Keeps class proportions in each fold |
| Regression, independent rows | `KFold` with `shuffle=True` | Simple random folds |
| Several rows per patient, user or machine | `GroupKFold` | Keeps all rows of one group in the same fold |
| Data ordered in time | `TimeSeriesSplit` | Validates only on rows later than the training rows |
| Very small dataset | `RepeatedStratifiedKFold` | Repeats k-fold with different shuffles for a steadier mean |
Grouped data is the most common source of silent error. Suppose a patient has ten records. A random split can put some of those records in training and others in validation. The model then recognizes the patient rather than learning the general pattern, and the score looks better than it will be on new patients. GroupKFold takes a groups argument so a whole group stays together.
from sklearn.model_selection import GroupKFold, cross_val_score
# groups holds one patient id per row, aligned with X_train
cv = GroupKFold(n_splits=5)
scores = cross_val_score(model, X_train, y_train, groups=groups, cv=cv)For time series, a random split lets the model train on the future and predict the past. TimeSeriesSplit always trains on earlier rows and validates on later ones.
Reading the results
Look at more than the mean.
- Spread. A large standard deviation means the estimate is unstable. Small data, rare classes and outliers all cause this.
- Training versus validation score.
cross_validatecan return training scores withreturn_train_score=True. A high training score with a much lower validation score points to overfitting. Low scores on both point to underfitting. - Comparison between models. Compare models on the same folds. Pass the same
cvobject, with a fixedrandom_state, to each. If two means differ by less than about one standard deviation, treat them as tied and prefer the simpler model.
from sklearn.model_selection import cross_validate
result = cross_validate(
model, X_train, y_train, cv=5,
scoring=["accuracy", "f1"], return_train_score=True,
)
print("train f1:", result["train_f1"].mean().round(3))
print("valid f1:", result["test_f1"].mean().round(3))The keys prefixed test_ hold the validation fold scores. The name is a scikit-learn convention and does not refer to your held-out test set.
Common errors
- Preprocessing before cross-validation. Fitting a scaler or imputer on all training rows, then cross-validating, lets each validation fold influence the preprocessing. Put every step in the pipeline.
- Selecting features on all data first. Choosing the columns most correlated with the target before cross-validating leaks the labels of the validation folds. Do feature selection inside the pipeline.
- Reusing the scores to pick among many options. If you try hundreds of settings and keep the best cross-validated score, that score is biased upward. The final test set is how you check for this.
- Ignoring the metric. Accuracy on an imbalanced problem hides failures. Use the metric chosen during problem framing through the
scoringargument. - Averaging nothing useful. Cross-validation estimates how a training procedure performs. It does not produce a final model. After choosing a configuration, fit once on the full training set.
Cost and trade-offs
Each fold is a full training run. Five-fold cross-validation of a slow model costs five times as much. Tuning multiplies this again: a grid of 20 settings with 5 folds means 100 fits. Use n_jobs=-1 to run folds in parallel, and start with a coarse search. For very large datasets, a single validation split is often enough because the validation set is itself large and the estimate is stable.
Exercise
A dataset has 12,000 rows from 800 customers, with about 15 rows per customer, and the goal is to predict churn for new customers. A teammate uses cross_val_score(model, X, y, cv=5) and reports an F1 of 0.97. Why might this be too optimistic, and what would you change?
Show answer
With plain stratified k-fold, rows from the same customer land in both training and validation folds. The model can learn customer-specific patterns and recognize those customers, which will not help on new customers. Use GroupKFold with a customer id as groups, so each customer appears in only one fold. Keep a test set split by customer as well, and expect a lower score.
Exercise
You cross-validate two pipelines with the same folds. Model A has a mean F1 of 0.912 with a standard deviation of 0.030. Model B, a much simpler model, has 0.905 with a standard deviation of 0.028. Which would you choose, and why?
Show answer
Model B. The 0.007 gap is much smaller than either standard deviation, so the models are effectively tied. The simpler model is cheaper, easier to explain and less likely to overfit.