Sub topic 3
K-fold cross-validation in a nutshell
This chapter assumes you know supervised learning basics (features, labels, training and test data), the idea of overfitting, and the scikit-learn fit, predict and score interface. The previous chapter showed that a single holdout split gives a noisy estimate of generalization error. K-fold cross-validation is the standard fix, and every later chapter builds on it.
The idea
A holdout split uses each example in only one role. A given example is either in the training set or in the test set, and the score depends on which examples happened to land in the test set. K-fold cross-validation (CV) removes this dependence by rotating the roles.
- Split the data into
kparts of roughly equal size, called folds. - For each fold
i, train a fresh model on the otherk - 1folds. - Score that model on fold
i, which it has never seen. - Report the
kscores, usually as a mean and a standard deviation.
Every example is used for testing exactly once and for training k - 1 times. The model is trained k times, and each model is thrown away after it is scored.
What the number estimates
The mean of the fold scores estimates the expected performance of a model trained on (k - 1)/k of your data, on new data from the same distribution. Three details in that sentence matter.
- It is not the score of one specific model. There are
kdifferent models, and none of them is the model you would deploy. CV estimates how well the training procedure performs. - The training sets are smaller than your full data. With
k = 5, each model sees 80% of the examples. If performance still improves with more data, the CV estimate is slightly pessimistic for a model trained on everything. - The test folds are not independent samples. The training sets overlap heavily, so the fold scores are correlated. The standard deviation of the fold scores describes how much the score varies between folds. It is not a proper confidence interval for the mean, and it usually understates the true uncertainty.
A manual loop
Writing the loop by hand shows what the library does. The model is a pipeline, so scaling is learned from the training folds only. The chapter on data leakage covers why that matters.
import numpy as np
from sklearn.base import clone
from sklearn.datasets import load_breast_cancer
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import KFold
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
X, y = load_breast_cancer(return_X_y=True)
model = make_pipeline(StandardScaler(), LogisticRegression(max_iter=1000))
kf = KFold(n_splits=5, shuffle=True, random_state=0)
scores = []
for fold, (train_idx, test_idx) in enumerate(kf.split(X)):
fold_model = clone(model) # a fresh, unfitted copy for every fold
fold_model.fit(X[train_idx], y[train_idx])
score = fold_model.score(X[test_idx], y[test_idx])
scores.append(score)
print(f"fold {fold}: train={len(train_idx)} test={len(test_idx)} accuracy={score:.3f}")
print(f"mean={np.mean(scores):.3f} std={np.std(scores):.3f}")The clone call is important. Without it you would keep refitting one object, and in some estimators (for example those with warm_start=True) state could carry over from one fold to the next.
The one-line version
cross_val_score does the same work. It clones the estimator, fits it on each training split, and scores it on each test split.
from sklearn.datasets import load_breast_cancer
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import KFold, cross_val_score
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
X, y = load_breast_cancer(return_X_y=True)
model = make_pipeline(StandardScaler(), LogisticRegression(max_iter=1000))
kf = KFold(n_splits=5, shuffle=True, random_state=0)
scores = cross_val_score(model, X, y, cv=kf)
print(scores)
print(f"{scores.mean():.3f} +/- {scores.std():.3f}")With the same splitter and the same random_state, this prints the same fold scores as the manual loop. The score is accuracy here because that is the default for classifiers. Pass scoring="roc_auc" or another metric name to change it.
When you need more than one metric, training times, or training-set scores, use cross_validate.
from sklearn.datasets import load_breast_cancer
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import KFold, cross_validate
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
X, y = load_breast_cancer(return_X_y=True)
model = make_pipeline(StandardScaler(), LogisticRegression(max_iter=1000))
kf = KFold(n_splits=5, shuffle=True, random_state=0)
result = cross_validate(
model, X, y, cv=kf,
scoring=["accuracy", "roc_auc"],
return_train_score=True,
)
for key in ["fit_time", "train_accuracy", "test_accuracy", "test_roc_auc"]:
print(key, result[key].round(3))A large gap between train_accuracy and test_accuracy is a quick sign of overfitting. The fit_time entries also give you a cost per fit, which becomes important when we count fits for nested CV.
Choosing k
The value of k trades off bias, variance and cost.
| k | Fits | Training size per fit | Typical effect |
|---|---|---|---|
| 2 | 2 | 50% | Cheap, but models see little data, so the estimate is pessimistic |
| 5 | 5 | 80% | Common default, good balance for medium datasets |
| 10 | 10 | 90% | Lower bias, twice the cost of `k = 5` |
| n (leave-one-out) | n | n - 1 examples | Lowest bias, often high variance and very expensive |
Larger k means training sets closer to the full data, so less pessimistic bias. It also means more fits and more overlap between training sets. Because of that overlap, the fold models are highly similar and the estimates become more correlated. Leave-one-out is rarely worth its cost outside very small datasets. In practice, k = 5 or k = 10 is the usual choice, and the difference between them is often smaller than the noise.
Edge cases and common mistakes
- Ordered data and
shuffle.KFoldwithoutshuffle=Truecuts the data into consecutive blocks. If rows are sorted by class, date or source, some folds can contain a single class or a different distribution from the rest. Shuffle with a fixedrandom_statefor reproducibility, unless the order carries meaning. Time-ordered data needs a different splitter, covered in the chapter on choosing splitters. - Class imbalance. Plain
KFoldcan produce folds with very few positives.cross_val_scoreuses stratified folds by default for classifiers when you pass an integercv, but when you pass aKFoldobject you get exactly what you asked for. Stratification is covered later. - Dependent rows. If several rows come from the same patient, user or device, a random split puts related rows on both sides and inflates the score. Grouped splitting handles this.
- Preprocessing outside the folds. Fitting a scaler, imputer or feature selector on all the data before CV lets information from the test folds shape the training. Put every learned step inside a
Pipeline. - Random seeds hide variance. A different
random_stategives a different partition and a slightly different mean. If two models differ by less than that spread, you have not shown that one is better. - Models that fail to converge. Warnings such as
ConvergenceWarningcan appear in only some folds. Check them, because a fold with a poorly fitted model drags the mean down for reasons unrelated to generalization.
Where this leads
K-fold CV is an evaluation tool for a fixed model. Hyperparameter tuning turns it into a selection tool, by running CV for many candidate settings and keeping the winner. That use changes what the scores mean, and the rest of this tutorial is about handling the change correctly.
Exercise
You run 10-fold cross-validation on a dataset of 1,000 rows and get a mean accuracy of 0.90 with a standard deviation of 0.02 across folds. (a) How many rows does each model train on, and how many models are fitted? (b) Is the deployed model, trained on all 1,000 rows, one of the models that produced the 0.90? (c) Why is 0.90 +/- 0.02 not a proper 95% confidence interval?
Show answer
(a) Each model trains on 900 rows and is scored on 100 rows, and 10 models are fitted. (b) No. The deployed model is a new fit on all rows. The 0.90 estimates the performance of the training procedure on 900-row training sets, which may be slightly pessimistic for a model trained on 1,000. (c) The fold scores are correlated because the training sets overlap heavily, so their standard deviation understates the uncertainty of the mean. The spread only describes variation between folds.