Sub topic 7
Cross-validation for more reliable estimates
This chapter assumes you know the train/validation/test split, how to fit a scikit-learn pipeline, and the difference between training and validation error.
Why one validation split is not enough
A single validation set gives one error number. With 40 samples and a 30% split, the validation set has only 12 points. A different random split could rank two models differently. The estimate is noisy, and you also lose data that the model could have trained on.
K-fold cross-validation reduces both problems. Every sample is used for validation exactly once and for training k-1 times.
How k-fold works
- Shuffle the training data and split it into k equal folds.
- For each fold, train on the other k-1 folds and score on the held-out fold.
- Average the k scores. The spread across folds tells you how stable the estimate is.
Comparing models with cross-validation
The code below scores polynomial models of three degrees on the same noisy sine data. Scaling sits inside the pipeline, so each fold fits its scaler on its own training portion only.
import numpy as np
from sklearn.model_selection import 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)
for degree in (1, 4, 15):
model = make_pipeline(PolynomialFeatures(degree), StandardScaler(), LinearRegression())
scores = cross_val_score(model, X, y, cv=5, scoring="neg_mean_squared_error")
print(degree, round(-scores.mean(), 3), round(scores.std(), 3))scikit-learn reports error metrics as negative values, so that a higher score is always better. Negate the mean to get the MSE back. Expect degree 4 to have the lowest mean error. Degree 15 should do worse and vary more between folds.
Common errors
- Fitting preprocessing outside the pipeline. If you scale all the data before calling
cross_val_score, each validation fold has influenced the scaler. This is data leakage and makes scores look better than they are. - Using the test set inside the loop. Run cross-validation on the training data only. Touch the test set once, at the end, for the final model.
- Ignoring the spread. If two models differ by less than the fold-to-fold standard deviation, you cannot say one is better.
- Unshuffled ordered data. For classification, use
StratifiedKFoldto keep class proportions. For time series, useTimeSeriesSplit, because shuffling lets the model train on the future.
Choosing k
Common choices are 5 and 10. A larger k trains on more data per round, so the estimate is less pessimistic. It also costs k model fits. Use 5 when training is slow.
Exercise
You standardise all 1,000 rows of your dataset with one StandardScaler, then run 5-fold cross-validation on the scaled data. Why is the score unreliable, and how do you fix it?
Show answer
The scaler computed its mean and standard deviation using rows that later land in validation folds, so information from the validation data leaks into training. Fix it by putting the scaler in a Pipeline with the model and passing the pipeline to crossvalscore, so the scaler is refit on the training folds in each round.