Holdout and K-Fold Cross-Validation
A metric is only as trustworthy as the data it is computed on. The data used to fit a model cannot judge it (the model has seen the answers), so some data has to be held back. How much, and how many times? With a single holdout split the score depends on which examples happened to land in the test part, sometimes by several points of accuracy. K-fold cross-validation uses every example for evaluation exactly once and tells you how much the score moves. This lesson measures both, and sets out the roles of the training, validation and test sets. The mechanics of the splitters are in Data Preparation; here the focus is on what the resulting numbers mean.
Three sets, three jobs
| Set | Used for | Touched |
|---|---|---|
| training | fitting the parameters (weights, splits) | every epoch |
| validation | choosing hyperparameters, features, the threshold, the model family; early stopping | many times |
| test | one final, unbiased estimate of performance on new data | once, at the end |
Every decision you make by looking at a score makes that score optimistic, because you kept what happened to work on that data. That is fine for the validation set, whose job is to be used for decisions, and fatal for the test set. If you look at the test score, change something and look again, the test set has become a second validation set and you no longer have an honest estimate.
Holdout: one split
The simplest scheme: shuffle, keep 20 to 30 % as a test (or validation) set, fit on the rest. It is cheap and is the right choice when data is plentiful (hundreds of thousands of rows) or a model takes hours to train. With small data it is noisy, as this experiment shows: the same model, the same data, twenty different random splits.
import numpy as np
from sklearn.datasets import load_breast_cancer
from sklearn.model_selection import train_test_split, cross_val_score, KFold
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.linear_model import LogisticRegression
X, y = load_breast_cancer(return_X_y=True)
model = make_pipeline(StandardScaler(), LogisticRegression(max_iter=1000))
holdout = []
for seed in range(20):
X_tr, X_te, y_tr, y_te = train_test_split(X, y, test_size=0.25, random_state=seed)
holdout.append(model.fit(X_tr, y_tr).score(X_te, y_te))
holdout = np.array(holdout)
print(f"20 holdout splits: mean {holdout.mean():.3f} std {holdout.std():.3f} min {holdout.min():.3f} max {holdout.max():.3f}")
cv_means = []
for seed in range(20):
scores = cross_val_score(model, X, y, cv=KFold(5, shuffle=True, random_state=seed))
cv_means.append(scores.mean())
cv_means = np.array(cv_means)
print(f"20 x 5-fold CV means: mean {cv_means.mean():.3f} std {cv_means.std():.3f} min {cv_means.min():.3f} max {cv_means.max():.3f}")20 holdout splits: mean 0.975 std 0.011 min 0.958 max 0.993
20 x 5-fold CV means: mean 0.977 std 0.004 min 0.967 max 0.982
On the 143-row test parts of 569 tumours, a single holdout accuracy lands anywhere between 0.958 and 0.993 depending on the seed (standard deviation 0.011). Report the lucky split and the model looks excellent; report the unlucky one and it looks merely good. The mean of a 5-fold CV moves much less from shuffle to shuffle (0.967 to 0.982, standard deviation 0.004), because every one of the 569 examples is used for scoring and the noise of the five folds averages out.
K-fold cross-validation
Split the shuffled data into equal folds. For , train on all folds except fold and score on fold . Every example is scored once, by a model that did not see it.
The cross-validation estimate is the mean of the fold scores,
where is the model trained without fold . Report it with the standard deviation of the fold scores. That spread describes how much the score moves between folds; it is not a confidence interval for the mean, because the folds share training data and are not independent. Common choices are or . Larger means each model sees more data (less pessimistic) and costs more fits; is leave-one-out, which is expensive and has high variance for most metrics.
Here it is from scratch, checked by handing the same folds to scikit-learn's cross_val_score, and next to scikit-learn's own shuffled KFold:
import numpy as np
from sklearn.datasets import load_breast_cancer
from sklearn.model_selection import cross_val_score, KFold
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.linear_model import LogisticRegression
from sklearn.base import clone
X, y = load_breast_cancer(return_X_y=True)
model = make_pipeline(StandardScaler(), LogisticRegression(max_iter=1000))
def kfold_splits(n, k, seed):
idx = np.random.default_rng(seed).permutation(n)
folds = np.array_split(idx, k)
return [(np.concatenate([folds[j] for j in range(k) if j != i]), folds[i]) for i in range(k)]
splits = kfold_splits(len(y), k=5, seed=0)
ours = []
for trn, val in splits:
m = clone(model).fit(X[trn], y[trn]) # a fresh model for every fold
ours.append(m.score(X[val], y[val]))
ours = np.array(ours)
print("fold sizes:", [len(val) for _, val in splits])
print("our loop: ", ours.round(3).tolist(), f" mean {ours.mean():.3f} +/- {ours.std():.3f}")
same = cross_val_score(model, X, y, cv=splits) # sklearn on the same folds
print("sklearn, our folds:", same.round(3).tolist(), f" mean {same.mean():.3f} +/- {same.std():.3f}")
sk = cross_val_score(model, X, y, cv=KFold(5, shuffle=True, random_state=0))
print("sklearn KFold: ", sk.round(3).tolist(), f" mean {sk.mean():.3f} +/- {sk.std():.3f}")fold sizes: [114, 114, 114, 114, 113]
our loop: [0.991, 0.974, 0.982, 0.974, 0.973] mean 0.979 +/- 0.007
sklearn, our folds: [0.991, 0.974, 0.982, 0.974, 0.973] mean 0.979 +/- 0.007
sklearn KFold: [0.965, 0.982, 0.956, 0.956, 1.0] mean 0.972 +/- 0.017
Our loop and scikit-learn agree fold by fold when they use the same folds (mean 0.979). With scikit-learn's own shuffle the folds are different and so are the scores: 0.972, with one fold at 1.0 and two at 0.956. Both are honest estimates of the same thing; the difference between them (0.007) is the noise you saw in the first example. clone matters: each fold must start from an unfitted model.
Putting it together: tune with CV, test once
The usual workflow: split off a test set first; on the training part, use cross-validation to compare hyperparameters; refit the best setting on the whole training part; score once on the test set.
import numpy as np
from sklearn.datasets import load_breast_cancer
from sklearn.model_selection import train_test_split, GridSearchCV, StratifiedKFold
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.linear_model import LogisticRegression
X, y = load_breast_cancer(return_X_y=True)
X_tr, X_te, y_tr, y_te = train_test_split(X, y, test_size=0.25, stratify=y, random_state=0)
pipe = make_pipeline(StandardScaler(), LogisticRegression(max_iter=5000))
search = GridSearchCV(pipe, {"logisticregression__C": [0.001, 0.01, 0.1, 1, 10, 100]},
cv=StratifiedKFold(5, shuffle=True, random_state=0))
search.fit(X_tr, y_tr) # CV on the 426 training rows only
for C, m, s in zip([0.001, 0.01, 0.1, 1, 10, 100], search.cv_results_["mean_test_score"], search.cv_results_["std_test_score"]):
print(f"C={C:<6} CV accuracy {m:.3f} +/- {s:.3f}")
print("best:", search.best_params_, f"CV {search.best_score_:.3f}")
print(f"test accuracy of the refitted best model (once): {search.score(X_te, y_te):.3f} on {len(y_te)} rows")C=0.001 CV accuracy 0.880 +/- 0.032
C=0.01 CV accuracy 0.948 +/- 0.021
C=0.1 CV accuracy 0.976 +/- 0.021
C=1 CV accuracy 0.981 +/- 0.012
C=10 CV accuracy 0.969 +/- 0.019
C=100 CV accuracy 0.960 +/- 0.019
best: {'logisticregression__C': 1} CV 0.981
test accuracy of the refitted best model (once): 0.958 on 143 rows
Cross-validation on the 426 training rows picks (CV accuracy 0.981). The refitted model scores 0.958 on the 143 test rows, lower than the CV estimate. That is not a bug: the best of six CV scores is slightly optimistic, and a single test set of 143 rows is itself noisy, as the holdout experiment showed. The test number is the one to report, together with its size.
The best CV score is itself slightly optimistic, because it is the maximum of six noisy estimates. When the CV score is what you report (no separate test set), use nested cross-validation: an inner loop chooses the hyperparameters, an outer loop scores the whole procedure (Nested Cross-Validation).
Pitfalls
- Preprocessing before splitting. A scaler, an imputer or a feature selector fitted on all the data leaks the validation folds into training. Put them in a
Pipelineso they are refitted inside each fold (Data Leakage). - Unshuffled k-fold on sorted data.
KFold()withoutshuffle=Truetakes consecutive blocks; if the file is sorted by class or date, folds differ systematically. UseStratifiedKFoldfor classification (next lesson) and time-aware splits for time series (Backtesting). - Reporting the test score of the model you picked by test score. Pick on validation, report on test.
- Over-reading small differences. If two models differ by less than the fold spread, the data does not separate them.
Practice
- With 1000 examples and 10-fold CV, how many models are trained, on how many examples each, and how many predictions are scored in total?
Answer
10 models, each on 900 examples; each scores its 100 held-out examples, so 1000 predictions in total, one per example.
- A team tunes 200 hyperparameter settings by checking each one's test-set accuracy and reports the best, 0.94. Why is this number biased, and what should they have done?
Answer
The maximum of 200 noisy estimates is biased upwards: some settings look good on this particular test set by chance. They should choose with cross-validation (or a validation set) on the training data and evaluate only the chosen setting once on the test set, or use nested CV.
Test yourself
Which set is used to choose hyperparameters?
- training set
- validation set (or CV folds of the training data)
- test set
- any of them
Why do 20 holdout splits of the same data give different accuracies?
- The model is random
- Each split puts different examples in the small test part, and the score depends on which
- The data changes
- Because of floating-point errors
In 5-fold cross-validation, how often is each example used for scoring?
- Never
- Exactly once
- Five times
- Four times
What does the standard deviation of the k fold scores describe?
- A 95 % confidence interval for the true score
- How much the score varies between folds; the folds are not independent, so it is not a confidence interval
- The bias of the model
- The training error