Sub topic 7
Cross-validation for more reliable estimates
This chapter assumes you know the train, validation, and test split, the difference between training and validation error, and scikit-learn's fit and predict workflow. It also assumes you have used pipelines.
Why one validation split is not enough
A single validation set gives you one number. That number depends on which rows landed in the validation set. With 40 samples and a 30% split, only 12 rows decide whether degree 4 beats degree 15. A different random seed can change the ranking.
Cross-validation reduces this dependence. It repeats the train and validate cycle several times on different partitions of the same data, then summarises the results. You get a mean error and a measure of how much that error varies.
How k-fold cross-validation works
In k-fold cross-validation you split the training data into k folds of roughly equal size. For each fold, you train on the other k-1 folds and score on the held-out fold. Every row is used for validation exactly once and for training k-1 times.
The mean estimates how the model family performs on unseen data. The standard deviation tells you how much to trust a difference between two models. If two candidates differ by less than the fold-to-fold spread, treat them as tied and prefer the simpler one.
Comparing models with cross-validation
The code below compares the same three polynomial degrees from earlier in the chapter. It scores each with 5-fold cross-validation. The scaler sits inside the pipeline, so each fold fits it on that fold's training rows only.
import numpy as np
from sklearn.model_selection import KFold, cross_val_score
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import PolynomialFeatures, StandardScaler
from sklearn.linear_model import LinearRegression
rng = np.random.default_rng(0)
X = rng.uniform(-3, 3, size=(40, 1))
y = np.sin(X).ravel() + rng.normal(0, 0.2, size=40)
cv = KFold(n_splits=5, shuffle=True, random_state=0)
for degree in (1, 4, 15):
model = make_pipeline(
PolynomialFeatures(degree), StandardScaler(), LinearRegression()
)
scores = cross_val_score(model, X, y, cv=cv, scoring="neg_mean_squared_error")
print(degree, round(-scores.mean(), 3), round(scores.std(), 3))scikit-learn scorers follow the convention that higher is better. Error metrics are therefore returned negated, as in neg_mean_squared_error. Negate the scores before reading them as errors.
Each call to cross_val_score clones the model and fits it from scratch for every fold. The model you pass in is not modified, and no fitted model is returned. To get a usable model, refit on all the training data after you have chosen.
Choosing k
The value of k trades bias against variance and cost.
- Small k (such as 3). Each model trains on only two thirds of the data. The estimate is pessimistic, because a model trained on less data usually does worse than one trained on all of it.
- Large k (such as 10). Each model trains on 90% of the data, so the estimate is less pessimistic. It also costs twice as many fits as k=5.
- k equal to the number of rows (leave-one-out). This is the least pessimistic, but it needs n fits. Its scores are also highly correlated with each other, so the average can still be noisy.
k=5 or k=10 is a sound default. With very small datasets, use repeated k-fold. It runs k-fold several times with different shuffles and pools all the scores.
Choosing the right splitter
Plain KFold assumes rows are independent and identically distributed. When that is false, it gives optimistic scores because information leaks across folds.
| Situation | Splitter | Reason |
|---|---|---|
| Classification with imbalanced classes | `StratifiedKFold` | Keeps class proportions similar in every fold, so no fold lacks a rare class. |
| Several rows per patient, user, or machine | `GroupKFold` | Keeps all rows of a group in the same fold. Otherwise the model sees the same patient in training and validation. |
| Time-ordered data | `TimeSeriesSplit` | Always validates on rows later than the training rows, so the model never trains on the future. |
| Small data, noisy estimates | `RepeatedKFold` | Averages over several different partitions. |
For classifiers, passing an integer such as cv=5 already uses stratified folds. For regressors it uses unstratified folds without shuffling. If your rows are sorted, for example by date or by label, an unshuffled KFold produces folds that are very different from each other. Set shuffle=True, or use a splitter that fits the structure of the data.
Keeping the test set untouched
Cross-validation lets you compare and tune models without spending the test set. The workflow is:
- Split off a test set once, and do not look at it.
- Run cross-validation on the remaining data to compare candidate models.
- Refit the chosen model on all of the non-test data.
- Score on the test set once and report that number.
import numpy as np
from sklearn.model_selection import train_test_split, cross_val_score
from sklearn.metrics import mean_squared_error
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import PolynomialFeatures, StandardScaler
from sklearn.linear_model import LinearRegression
rng = np.random.default_rng(0)
X = rng.uniform(-3, 3, size=(120, 1))
y = np.sin(X).ravel() + rng.normal(0, 0.2, size=120)
X_dev, X_test, y_dev, y_test = train_test_split(X, y, test_size=0.2, random_state=0)
best_degree, best_mse = None, float("inf")
for degree in (1, 2, 3, 4, 5, 8, 12):
model = make_pipeline(
PolynomialFeatures(degree), StandardScaler(), LinearRegression()
)
scores = cross_val_score(
model, X_dev, y_dev, cv=5, scoring="neg_mean_squared_error"
)
mse = -scores.mean()
if mse < best_mse:
best_degree, best_mse = degree, mse
final = make_pipeline(
PolynomialFeatures(best_degree), StandardScaler(), LinearRegression()
).fit(X_dev, y_dev)
print("chosen degree:", best_degree)
print("cross-validated MSE:", round(best_mse, 3))
print("test MSE:", round(mean_squared_error(y_test, final.predict(X_test)), 3))The cross-validated MSE of the winner is slightly optimistic. You picked it because it had the lowest score among several candidates, so some of that advantage is luck. The test MSE is the honest figure. The more candidates you compare, the larger this selection effect becomes. When you need an unbiased estimate of the whole tuning procedure without a separate test set, use nested cross-validation. It runs an outer loop for evaluation and an inner loop for tuning.
Common errors
- Fitting a scaler or selector before the split. Calling
StandardScaler().fit_transform(X)on all rows lets validation statistics influence training. Put preprocessing in a pipeline so it is refit inside each fold. - Reading the mean without the spread. A gap of 0.01 in mean MSE means nothing if the standard deviation across folds is 0.05.
- Using cross-validation scores as test results. After you tune against them, they are no longer an unbiased estimate.
- Wrong splitter for the data. Grouped or time-ordered data with plain
KFoldgives scores that look good and fail in production. - Forgetting to refit.
cross_val_scorereturns scores only. You still need to callfiton the full training data before predicting.
Exercise
You run 5-fold cross-validation on a dataset where each of 200 patients contributes about 10 rows. The score is much better than the score on a new group of patients. What is the likely cause, and which splitter fixes it?
Show answer
Plain KFold put rows from the same patient into both the training and validation folds, so the model was scored on patients it had already seen. Use GroupKFold with the patient ID as the groups argument, so each patient appears in only one fold at a time.
Exercise
Model A has a mean cross-validated MSE of 0.052 with a fold standard deviation of 0.030. Model B has a mean of 0.049 with a standard deviation of 0.028. A is a degree-3 polynomial and B is degree 9. Which would you choose, and why?
Show answer
Choose A. The 0.003 difference in means is much smaller than the fold-to-fold spread, so the two are effectively tied. When estimates are tied, the simpler model is less likely to overfit.