Foundations to Frontier
Tests
D. Classical Machine Learning › D0 Core Concepts (concept pages)

Cross-Validation: k-Fold, Stratified, Grouped, Leave-One-Out, Time-Series and Nested

Cross-validation reuses limited data for evaluation: split it into k folds, train on k − 1 of them, test on the remaining one, and rotate so every example is tested once. Variants respect the data's structure: stratified folds keep class proportions, grouped folds keep groups together, leave-one-out uses single examples, time-series splits only train on the past, and nested cross-validation tunes hyperparameters inside an outer loop so the final estimate stays honest. This page explains each variant, the bias and variance of CV estimates, and how to report them. In the exercises you implement all the splitters and nested CV for k-nearest neighbours; then you measure how precise CV estimates are for different k and how optimistic the best tuned score is compared with nested CV.

Level 0: Foundation

★☆☆☆☆ Introductory⏱ 5 minGeneral audience. No mathematics required.

Taking turns being the test

With only a little data, keeping a big test set wastes examples. Instead, cut the data into, say, five slices. Train on four slices and test on the fifth; then let another slice be the test, and so on, until every slice has had its turn. The average of the five scores is the cross-validation score, and every example was tested exactly once.

Cross-validation splitters, side by side
classgroupAAAABBBBCCCCDDDDEEEEFFFFround 1round 2round 3round 4
rounds: 4 · rare-class examples per test fold: 1, 2 · rounds where a group sits on both sides: 4
Purple marks the rare class (6 of 24); letters are groups such as engines or patients. Plain k-fold can leave a test fold with no rare examples; stratified k-fold spreads them evenly; group k-fold never splits a group; leave-one-out uses every example once as a 1-element test set; the time-series split only trains on the past, optionally leaving a gap before each test block.
Why engineers care

Flight-test campaigns, rare failure logs and labelled lab samples are small and expensive. Cross-validation lets you compare models on such data without throwing a large share away, as long as the folds respect engines, flights or time.

📝 Quick check (Level 0)
0/3 answered
  1. 1. In 5-fold CV, how many times is each example tested?
  2. 2. The CV score is…
  3. 3. In the demo, which splitter keeps every group on one side?

Level 1: Beginner

★★☆☆☆ Basic⏱ 20 minSecondary-school mathematics: arithmetic and elementary algebra.

Choosing a splitter

Splitter Use when Note
k-fold (k = 5 or 10), shuffled i.i.d. rows default
stratified k-fold classification, especially imbalanced same class ratio per fold
group k-fold repeated rows per entity groups never straddle
leave-one-out (k = n) very small n, cheap models high variance and cost
time-series split temporal data expanding or sliding window, optional gap
repeated k-fold small data, want a more stable mean repeat with new shuffles
nested CV tuning and evaluating on the same data inner loop tunes, outer loop evaluates
from sklearn.model_selection import StratifiedKFold, GroupKFold, TimeSeriesSplit, cross_val_score, GridSearchCV
cv = StratifiedKFold(n_splits=5, shuffle=True, random_state=0)
print(cross_val_score(model, X, y, cv=cv).mean())
inner = GridSearchCV(model, {"n_neighbors": [1, 5, 15]}, cv=5)
print(cross_val_score(inner, X, y, cv=cv).mean())        # nested CV
📝 Quick check (Level 1)
0/3 answered
  1. 1. Sensor data ordered in time call for…
  2. 2. Nested CV is needed when…
  3. 3. Leave-one-out on n examples trains…

Level 2: Intermediate

★★★☆☆ Intermediate⏱ 35 minUndergraduate students and practising engineers.

What the CV score estimates

Each fold model is trained on (k − 1)/k of the data, so CV estimates the performance of a model trained on slightly less data. The estimate is therefore slightly pessimistic, by less as k grows. Its variance comes from the finite test folds and from the particular dataset. Fold scores are correlated (training sets overlap), so the naive standard error std/√k understates the uncertainty.

CV estimates the expected performance of the procedure over datasets of this size, more than the performance of the one model you will deploy (Bates, Hastie and Tibshirani, 2023).

Tuning picks the best of many CV scores, and the maximum of noisy estimates is biased upward. Nested CV wraps the whole tuning procedure in an outer loop, so each outer test fold never influences the choice made for it.

🐍 Exercise 1: cross-validation splitters and nested CV
Implement shuffled k-fold, stratified k-fold (round-robin per class), group k-fold (balanced greedy assignment of groups), leave-one-out and an expanding-window time-series split with a gap; score k-nearest neighbours with CV; implement nested CV that tunes the number of neighbours in an inner loop.
📝 Quick check (Level 2)
0/3 answered
  1. 1. Why is k-fold CV slightly pessimistic?
  2. 2. Why is the best CV score after tuning optimistic?
  3. 3. std/√k of fold scores understates uncertainty because…

Level 3: Advanced

★★★★☆ Advanced⏱ 30 minGraduate level, with full derivations and proofs.

Practical guidance

  • Use k = 5 or 10 with shuffling (except for time). Repeat with several shuffles for small data; report mean ± standard deviation over folds and the number of repeats.
  • Fit every preprocessing step inside the folds with a Pipeline. CV only protects you if the whole procedure is cross-validated.
  • Leave-one-out is nearly unbiased but costly and not lower-variance in practice. It is exact and cheap for some models (linear smoothers, kNN).
  • After CV, refit the chosen configuration on all the data for deployment. The CV score describes that procedure.
  • Comparing models: use the same folds for all models (paired comparison, D0.15).

Interview questions.

  • Why not tune on the test set? It turns the test set into a validation set, leaving no unbiased estimate.
  • When would you use group k-fold? When several rows share an entity whose identity could be memorised.
📝 Quick check (Level 3)
0/3 answered
  1. 1. After choosing hyperparameters by CV, the deployed model is…
  2. 2. Comparing two models fairly with CV requires…
  3. 3. Scaling must be fitted…

Level 4: Expert

★★★★★ Expert⏱ 30 minResearchers: original papers and open problems.

How precise is cross-validation?

Exercise 1.

  • Stratified folds of 20 negatives and 5 positives put exactly one positive in each fold.
  • Group k-fold balances 7 groups into folds of 7, 7 and 6 rows without splitting any group.
  • The time-series split with a gap trains on 0–1 before testing 3–5.
  • Nested CV on 120 points chooses k = 15 in four of five outer folds.

Exercise 2a: precision of the CV estimate. Setup:

  • 9-nearest-neighbour classification of two overlapping Gaussians;
  • datasets of n = 60 examples, 150 of them;
  • the true accuracy of each trained model is measured on 4 000 fresh points (mean 0.825).
Splitter Bias (CV − truth) SD of estimate RMSE Correlation with this model’s truth
2-fold −0.009 0.057 0.056 0.27
5-fold −0.008 0.053 0.052 0.22
10-fold −0.007 0.052 0.051 0.24
leave-one-out −0.008 0.055 0.054 0.25

All splitters are slightly pessimistic, as theory predicts. With 60 examples, every estimate is uncertain by about ±5 points: the 60 test predictions are a small sample whatever k is. The choice of k barely matters. The weak correlation (about 0.2–0.3) shows that CV tells you how well the method does on datasets like this, not how good this particular fitted model is.

Exercise 2b: tuning k by CV (k from 1 to 39, 5-fold, 60 datasets).

Quantity Accuracy
best CV score (what you would report) 0.853
nested CV estimate 0.810
true accuracy of the tuned model 0.825

Reporting the best CV score overstates accuracy by 2.8 points. Nested CV is honest (1.4 points pessimistic, from smaller training sets).

🐍 Exercise 2 (research): how good are cross-validation estimates?
Repeatedly draw small datasets; compare 2-fold, 5-fold, 10-fold and leave-one-out estimates of a kNN classifier's accuracy with its true accuracy on fresh data (bias, SD, RMSE, correlation); then tune the number of neighbours and compare the best CV score, a nested CV estimate and the true accuracy of the tuned model.

Cross-validation in AI, robotics and aerospace

  • Small engineering datasets (test-stand runs, wind-tunnel campaigns): repeated, grouped CV by run.
  • Predictive maintenance: time-series CV with a gap equal to the prediction horizon.
  • Remote sensing: spatial block CV to avoid optimistic estimates from autocorrelation.
  • AutoML systems: inner CV for model selection, with outer validation for reporting.

References

  1. M. Stone (1974). “Cross-validatory choice and assessment of statistical predictions.” JRSS B 36(2).
  2. R. Kohavi (1995). “A study of cross-validation and bootstrap for accuracy estimation and model selection.” IJCAI.
  3. Y. Bengio, Y. Grandvalet (2004). “No unbiased estimator of the variance of K-fold cross-validation.” JMLR 5.
  4. G. C. Cawley, N. L. C. Talbot (2010). “On over-fitting in model selection and subsequent selection bias in performance evaluation.” JMLR 11.
  5. S. Bates, T. Hastie, R. Tibshirani (2023). “Cross-validation: what does it estimate and how well does it do it?” JASA 119.