Sub topic 10
Cross-validation
This chapter assumes you can split data with train_test_split, know what a validation set is, and have used a scikit-learn estimator with fit and score.
Why a single validation set is not enough
A single validation split gives one score from one random draw. On a small dataset, a different draw can change that score by several points. You might pick a model because it got lucky on one split.
Cross-validation (CV) reduces this noise. It repeats the train/validate cycle several times on different parts of the training data and averages the results.
How k-fold works
In k-fold cross-validation, you cut the training data into k equal parts called folds. You then run k rounds. In each round, one fold is the validation fold and the other k-1 folds are used for training. Each row is used for validation exactly once.
The average is a more stable estimate than any single split. The spread of the scores (their standard deviation) also tells you how much the estimate varies.
Where the test set fits
Cross-validation replaces the fixed validation set. It does not replace the test set. The workflow is:
- Hold out the test set first and leave it alone.
- Run cross-validation on the training portion to compare models or tune hyperparameters.
- Pick the final model, fit it on the full training portion, and score it once on the test set.
Example with a pipeline
The code below uses StratifiedKFold, which keeps class proportions similar in every fold. This matters for imbalanced classes, as in the stratified splits chapter. Setting shuffle=True with a random_state makes the folds random but repeatable.
The scaler sits inside a pipeline. cross_val_score refits the whole pipeline on the training folds of each round, so the scaler never sees the validation fold.
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))scores is an array of five accuracies. Print scores.std() as well to see how stable the estimate is.
Common errors
- Scaling before cross-validation. If you call
StandardScaler().fit_transformon the training set and then cross-validate, each validation fold has already influenced the scaler. Put preprocessing in the pipeline. - Cross-validating on all the data, then testing on part of it. The test rows must be removed before any CV starts.
- Reusing CV scores for endless tuning. If you try hundreds of settings and keep the best CV score, that score is optimistic. The untouched test set is your check.
- Plain k-fold on dependent rows. If several rows come from the same patient, or the rows are ordered in time, random folds leak information. Later chapters cover grouped and time-ordered splitting.
Choosing k
| k | Effect |
|---|---|
| 5 | Common default. Each model trains on 80% of the data and the cost is moderate. |
| 10 | Less biased estimate, since each model trains on 90%. It takes twice as long as k=5. |
| n (leave-one-out) | Uses nearly all the data for training. It is very slow and its scores vary a lot. |
Exercise
You run 5-fold cross-validation and get accuracies of 0.91, 0.93, 0.92, 0.90 and 0.94. A colleague then tunes 200 hyperparameter settings with the same CV and reports the best CV score as the expected accuracy on new data. Why is that report too optimistic, and what should you do instead?
Show answer
Picking the best of 200 settings selects the one that happened to fit these folds well, so its CV score is biased upward. Keep a test set that CV and tuning never touched. After choosing the final setting, fit on the full training set and report the score from that single test-set evaluation.