Sub topic 10
Cross-validation
This chapter assumes you can run a train_test_split, know why a validation set exists, and have fit a scikit-learn estimator before. Cross-validation builds on all three.
Why one validation split is not enough
A single validation set gives you one score, and that score depends on which rows happened to land in it. With 500 rows and a 20% validation set, only 100 rows decide your choice between two models. Move a few hard rows from one side to the other and the ranking can flip. That effect is noise, not a real difference between the models.
Cross-validation (CV) reduces the noise. It repeats the train-and-validate cycle several times on different partitions of the same training data. Every row is used for validation exactly once, and the scores are averaged.
How k-fold works
In k-fold cross-validation you split the training data into k equal parts called folds. For each round, one fold is the validation fold and the other k−1 folds are the training data. You fit a fresh model, score it on the held-out fold, and move on. After k rounds you have k scores.
Two points are easy to miss:
- Each round trains a new model from scratch. CV does not produce one final model. It estimates how well a modelling procedure (preprocessing, algorithm and settings) performs.
- The test set is not part of this process. You split it off first, and CV runs only on the training portion.
Running cross-validation in scikit-learn
cross_val_score takes an estimator, the data and a splitter. The splitter is passed as cv. The pipeline matters here: it makes the scaler refit on only the training folds in each round, so the validation fold never influences the scaling statistics.
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 make_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 = make_pipeline(StandardScaler(), 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)
print("CV accuracy:", scores.mean())
model.fit(X_train, y_train)
print("Test accuracy:", model.score(X_test, y_test))The last two lines show the intended order. CV guides your decisions on the training data. You fit on all training data once, and you look at the test set once at the end.
Choosing the splitter
Passing an integer such as cv=5 works, but an explicit splitter makes your choices visible.
| Splitter | Use it when | Note |
|---|---|---|
| `KFold` | Regression, or balanced classes | Without `shuffle=True`, folds are contiguous blocks of rows |
| `StratifiedKFold` | Classification, especially imbalanced classes | Keeps class proportions in every fold |
| `GroupKFold` | Several rows come from the same person, device or patient | Keeps each group on one side of every split |
| `TimeSeriesSplit` | Rows are ordered in time | Validation rows always come after training rows |
For classifiers, cross_val_score uses stratified folds by default when you pass an integer. If your data file is sorted by class or by date and you use plain KFold without shuffling, each fold may contain a different kind of data and the scores will mislead you. Set shuffle=True and random_state for ordinary tabular data. Do not shuffle time-ordered data, and use TimeSeriesSplit for it.
Grouped and time-ordered data are covered in later chapters. The rule for now is that CV only works if the validation fold is a fair stand-in for new data. If related rows sit on both sides of a split, the scores will be too high.
Comparing models fairly
To compare candidates, give them the same folds. A fixed splitter object with a fixed random_state does that, because it produces the same partitions each time it is used.
from sklearn.datasets import load_breast_cancer
from sklearn.ensemble import RandomForestClassifier
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import StratifiedKFold, cross_val_score, train_test_split
from sklearn.pipeline import make_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
)
cv = StratifiedKFold(n_splits=5, shuffle=True, random_state=42)
candidates = {
"logreg": make_pipeline(StandardScaler(), LogisticRegression(max_iter=1000)),
"forest": RandomForestClassifier(n_estimators=200, random_state=42),
}
for name, candidate in candidates.items():
scores = cross_val_score(candidate, X_train, y_train, cv=cv)
print(f"{name}: mean={scores.mean():.3f} std={scores.std():.3f}")Read both numbers. The mean is your estimate. The standard deviation across folds shows how much the score moves from one partition to another. If two models differ by less than that spread, you cannot say one is better. The folds share training data, so they are not independent, and the spread understates the true uncertainty. Treat it as a rough guide, not a confidence interval.
Choosing k
| k | Effect |
|---|---|
| 3 | Fast, but each model trains on only two thirds of the data, so scores are pessimistic |
| 5 or 10 | Common defaults, with a good balance of bias and cost |
| n (leave-one-out) | Almost no pessimism, but n model fits, and the scores have high variance |
A larger k means each training set is closer to the full training set, which makes the estimate less pessimistic. It also means more fits and more compute. For slow models, 5 folds is usually the practical choice. For small datasets, 10 folds or repeated CV (RepeatedStratifiedKFold) gives steadier estimates.
Tuning hyperparameters with CV
GridSearchCV runs CV for every setting you list and keeps the best one. By default it then refits on the full training data you gave it.
The best CV score from a search is optimistic. You picked the maximum of many noisy numbers, so some of that score is luck. If you need an honest estimate of the whole tuning procedure, wrap the search in an outer CV loop. This is called nested cross-validation.
from sklearn.datasets import load_breast_cancer
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import (
GridSearchCV, StratifiedKFold, cross_val_score, train_test_split
)
from sklearn.pipeline import make_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
)
pipe = make_pipeline(StandardScaler(), LogisticRegression(max_iter=1000))
inner = StratifiedKFold(n_splits=5, shuffle=True, random_state=1)
outer = StratifiedKFold(n_splits=5, shuffle=True, random_state=2)
search = GridSearchCV(
pipe, {"logisticregression__C": [0.01, 0.1, 1, 10]}, cv=inner
)
nested_scores = cross_val_score(search, X_train, y_train, cv=outer)
print("Nested CV accuracy:", nested_scores.mean())
search.fit(X_train, y_train)
print("Best C:", search.best_params_["logisticregression__C"])
print("Test accuracy:", search.score(X_test, y_test))The inner loop picks C. The outer loop scores that selection procedure on folds the search never saw. Nested CV costs about k × k × (number of settings) fits, so use it when you need the estimate, not on every experiment.
Common errors
- Preprocessing outside the pipeline. Scaling, imputing, feature selection or target encoding done before CV leaks validation-fold information into training. Put every step that learns from data inside the pipeline.
- Reporting the tuned CV score as final performance. After many comparisons the best CV score is biased upward. Use nested CV, or confirm once on the untouched test set.
- Reusing the test set inside CV. If you cross-validate on all the data and then also report a "test" score from the same rows, the two numbers are not independent evidence.
- Unshuffled folds on sorted data. Plain
KFoldon a file sorted by label produces folds with very different class mixes. - Ignoring dependence between rows. Repeated measurements of the same subject need
GroupKFold. Time-ordered data needsTimeSeriesSplit. - Treating CV models as the final model.
cross_val_scorefits temporary models and discards them. Fit the chosen pipeline once on the full training set afterwards.
Exercise
You scale all of your data with StandardScaler().fittransform(X), then run 5-fold crossval_score on the scaled data. A colleague says this is harmless because the model never sees the labels of the validation fold. What is wrong with that reasoning, and what is the fix?
Show answer
Leakage does not require labels. The scaler's mean and standard deviation were computed from every row, including rows that later act as validation rows, so each validation fold has influenced the training features. The scores are therefore slightly optimistic. The fix is to put the scaler and the model in one pipeline (makepipeline(StandardScaler(), model)) and pass the pipeline to crossval_score, so the scaler is refit on the training folds of each round only.
Exercise
GridSearchCV reports a best CV accuracy of 0.97 for your tuned model. Why might the real accuracy on new data be lower, and name two ways to get a more honest estimate.
Show answer
The best score is the maximum over many noisy CV results, so it is biased upward by selection. Two honest estimates are nested cross-validation (an outer CV loop around the search) and a final evaluation on a test set that was set aside before any tuning and is used once.