Level 3 In-Depth AI · Classical Machine Learning
Cross-Validation
Instead of trusting one lucky or unlucky split, rotate which part of the data is held out and average the results. A more reliable score from the same data, at the price of training the model several times.
- Level
- ●●●●● Easy
- Reading
- 11 min
- To learn it well
- 45 minutes to read, an hour to practise
- Builds on
- 5 concepts →
- Quiz
- 5 questions ↓
Read first
Training, Validation and Test SetsThis leads to
Hyperparameter TuningThe full path from zero — 5 concepts before this one
- What Is AI?
- How Machines Learn
- Supervised, Unsupervised and Reinforcement Learning
- Supervised Learning
- Training, Validation and Test Sets
- Cross-Validation
Read them roughly in this order. See it on the concept map →
Why it matters
A single train/validation split (Training, Validation and Test Sets) has two problems. It wastes data: the examples set aside for validation never help the model learn. And it is noisy: which examples happen to land in the validation set changes the score, sometimes a lot. On the breast-cancer dataset used below, the same model scores anywhere from 94.7% to 99.1% depending only on how the data was shuffled. If you compare two models on one split, the "winner" may simply have drawn the easier validation set.
Cross-validation fixes both problems by rotating the validation role through the whole dataset and averaging. It is the standard way to compare models, choose Regularization: L1 and L2 strength and other hyperparameters, and report performance on small and medium datasets. Most of scikit-learn's model-selection tools (GridSearchCV, cross_val_score, LassoCV, learning_curve) are built on it.
The intuition
Imagine judging a cook by one dish. If they happen to make their speciality, you overrate them. If they make the one thing they are bad at, you underrate them. Taste five different dishes and average, and your judgement is much more reliable.
Cross-validation does this with data. Cut the data into, say, five equal parts called folds. Train on four folds and validate on the fifth. Then do it again with a different fold held out, and again, until every fold has had its turn as the validation set. You now have five scores instead of one. Their average is a steadier estimate, and their spread tells you how much to trust it.
Every example is used for validation exactly once and for training four times. Nothing is wasted.
Key idea k-fold cross-validation: split the data into folds, train times, each time validating on a different fold, and average the scores. It gives a more reliable estimate than one split, uses all the data, and also tells you how much the score varies.
How it works
k-fold cross-validation step by step
- Shuffle the examples (unless their order matters; see time series below).
- Split them into folds of roughly equal size. Common choices are or .
- For : train a fresh model on all folds except fold , and compute its score on fold .
- Report the mean and the standard deviation of the .
Every preprocessing step (scaling, filling missing values, feature selection) must be fitted inside step 3, on the training folds only, or information leaks from the validation fold into the model. Wrapping the steps in a scikit-learn Pipeline does this automatically.
A worked example by hand
A model gets these accuracies on five folds: 0.92, 0.88, 0.95, 0.90, 0.85.
- Mean: .
- Deviations from the mean: . Squared: . Their average is , and its square root is the standard deviation, .
- So the result is about .
How should you read that ±0.03? It is the spread of individual fold scores. The uncertainty of the mean is smaller, roughly . That formula is only approximate, because the folds share most of their training data and so their scores are not independent. Treat it as a rough guide. Now suppose a second model scores a mean of 0.91. A 0.01 difference, well within the noise, is not evidence that it is better. A useful habit is to compare models fold by fold, on the same folds: if model B beats model A on all five folds, that is far more convincing than a small difference in means.
How many folds?
- or is the usual choice. Each model trains on 80% or 90% of the data, close to what the final model will see, and the cost is 5 or 10 training runs.
- Leave-one-out cross-validation (LOOCV) sets equal to the number of examples: train on everything but one example, test on that one, repeat for each example. It wastes the least data but costs training runs, and its estimate can be quite variable. It is mainly used for tiny datasets, or for models such as linear regression where a mathematical shortcut makes it cheap.
- Repeated cross-validation runs k-fold several times with different shuffles and averages everything. It smooths out the luck of how the folds were cut.
Stratified k-fold
For classification, especially with rare classes, a fold may by chance get too few examples of some class. Stratified k-fold builds each fold so that it keeps the class proportions of the whole dataset. With 10% positives and 5 folds, each fold gets 10% positives. Scikit-learn uses stratified folds by default when you pass a classifier and an integer cv=5 to its helpers.
Group k-fold
When examples come in groups (several scans per patient, several sessions per user), a random fold assignment lets the same group appear in both training and validation, which inflates scores. Group k-fold assigns whole groups to folds, so each validation fold contains only groups the model never trained on. In scikit-learn: cross_val_score(model, X, y, groups=patient_ids, cv=GroupKFold(n_splits=5)). Use it whenever, in real use, the model will face new groups.
Time series: forward chaining
With data ordered in time, a validation fold in the middle would let the model learn from the future. Instead use forward chaining (also called rolling-origin or walk-forward validation): train on months 1–6 and validate on month 7; train on 1–7, validate on 8; and so on. Each validation period always comes after its training data. Scikit-learn's TimeSeriesSplit does this. See Time Series Forecasting.
Nested cross-validation
Here is a subtle trap. Suppose you use 5-fold cross-validation to try 20 values of a hyperparameter and pick the one with the best average score. That best score is now optimistic: out of 20 noisy estimates you chose the highest, and some of its height is luck. The more options you try, the bigger this selection bias. Gavin Cawley and Nicola Talbot showed in 2010 that it can be as large as the differences between learning algorithms that people report.
If you need an honest estimate of how well "tune, then train" works, use nested cross-validation: an outer loop for scoring and an inner loop for tuning.
The outer score never comes from data used for tuning. The cost is high: 5 outer folds × 5 inner folds × 5 candidate settings = 125 training runs plus refits. Use it when you need a trustworthy number from a small dataset, for example in a paper or a medical study. On larger datasets a simpler scheme does the same job: tune with cross-validation on the training data, then score once on a separate test set.
When is a single split enough?
Cross-validation multiplies training cost by . It is worth it when:
- the dataset is small or medium (up to perhaps tens of thousands of examples), so a single validation set would be small and noisy;
- training is cheap (linear models, trees, boosting on tabular data);
- you are comparing models whose scores are close.
A single validation split is usually enough when:
- the dataset is large (hundreds of thousands of examples or more), so the validation set alone gives a precise estimate;
- training is expensive: nobody trains a large neural network five times to cross-validate it;
- the data has a natural split that matters more than precision, such as "the last month" for a forecasting model.
In code
From scratch: shuffle the row numbers, cut them into five folds, and loop. Note that the scaler lives inside the pipeline, so it is refitted on each round's training folds.
import numpy as np
from sklearn.datasets import load_breast_cancer
from sklearn.linear_model import LogisticRegression
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
X, y = load_breast_cancer(return_X_y=True)
rng = np.random.default_rng(0)
folds = np.array_split(rng.permutation(len(X)), 5) # 5 disjoint groups of rows
scores = []
for k in range(5):
val = folds[k]
train = np.concatenate([folds[j] for j in range(5) if j != k])
model = make_pipeline(StandardScaler(), LogisticRegression(C=0.1))
model.fit(X[train], y[train]) # fresh model each fold
scores.append(model.score(X[val], y[val]))
print("fold accuracies:", np.round(scores, 3))
print(f"mean {np.mean(scores):.3f} std {np.std(scores):.3f}")
# fold accuracies: [0.982 0.965 1. 0.974 0.965]
# mean 0.977 std 0.013
With scikit-learn: how lucky can one split be, the standard stratified 5-fold estimate, and nested cross-validation around a grid search over C:
import numpy as np
from sklearn.datasets import load_breast_cancer
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import (StratifiedKFold, GridSearchCV,
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)
model = make_pipeline(StandardScaler(), LogisticRegression(C=0.1))
# How much does a single 80/20 split depend on luck?
singles = [model.fit(Xa, ya).score(Xb, yb) for Xa, Xb, ya, yb in
(train_test_split(X, y, test_size=0.2, random_state=s) for s in range(20))]
print(f"20 single splits: min {min(singles):.3f} max {max(singles):.3f}")
# Stratified 5-fold cross-validation
cv = StratifiedKFold(n_splits=5, shuffle=True, random_state=0)
scores = cross_val_score(model, X, y, cv=cv)
print(f"5-fold CV: {scores.mean():.3f} +/- {scores.std():.3f}")
# Nested CV: the inner loop picks C, the outer loop scores the whole procedure
inner = GridSearchCV(model, {"logisticregression__C": [0.01, 0.1, 1, 10, 100]}, cv=5)
outer = cross_val_score(inner, X, y, cv=cv)
print(f"nested CV: {outer.mean():.3f} +/- {outer.std():.3f}")
# 20 single splits: min 0.947 max 0.991
# 5-fold CV: 0.975 +/- 0.012
# nested CV: 0.974 +/- 0.010
A single split could have reported anything from 94.7% to 99.1%. Cross-validation pins it near 97.5%. The nested estimate, 97.4%, is barely lower here because only five values of C were tried and the model is not very sensitive to them. With a big search over a flexible model, the gap can be much larger. The odd name logisticregression__C is how scikit-learn addresses a parameter of one step inside a pipeline: step name, two underscores, parameter name.
Common pitfalls
- Preprocessing outside the folds. Scaling, imputing, selecting features or oversampling rare classes on the full data before cross-validating leaks information into every validation fold. Put every step in a
Pipelineand cross-validate the pipeline. - Reporting the tuned CV score as the final result. The best score from a search is optimistic. Report nested CV or a held-out test set.
- Random folds on grouped or time-ordered data. Use
GroupKFoldorTimeSeriesSplit. A random split of patients' scans or of daily prices gives scores you won't see in practice. - Over-reading small differences. Compare models on the same folds and look at fold-by-fold wins, not just means that differ in the third decimal place.
- Forgetting the final model. Cross-validation evaluates a procedure; it doesn't hand you one model. After choosing, retrain on all the training data to get the model you deploy.
Watch out Cross-validation does not protect against leakage that is built into the data itself: duplicated examples, features recorded after the outcome, or the same patient under two IDs. It only rotates the split. Fix the data first (Training, Validation and Test Sets, Data Cleaning and Preparation).
Where it leads
- Hyperparameter Tuning: grid, random and Bayesian search all use cross-validation (or a validation set) as their judge.
- Regularization: L1 and L2:
RidgeCV,LassoCVandLogisticRegressionCVpick the penalty strength by cross-validation. - Overfitting and the Bias–Variance Tradeoff: learning and validation curves are computed with cross-validation.
- Evaluation Metrics: what score to average across folds.
- Time Series Forecasting: backtesting with forward chaining.
- Random Forests and Bagging: the out-of-bag estimate, a free alternative to cross-validation built into bagging.
A bit of history
The idea of testing a prediction rule on data not used to build it goes back at least to the 1930s. Mervyn Stone (1974) and Seymour Geisser (1975) formalised cross-validation as a general method for choosing and assessing statistical models, and leave-one-out became popular because for linear models it can be computed without refitting. Ron Kohavi's widely cited 1995 study compared cross-validation with the bootstrap on real datasets and recommended stratified 10-fold cross-validation as a default, a choice many practitioners still use. Cawley and Talbot's 2010 paper made the case for nested cross-validation by showing how badly selection bias can mislead. As datasets and models grew, deep learning moved mostly to single validation splits, but for tabular data and small datasets cross-validation remains standard.
Try it
- Compute by hand the mean and standard deviation of the fold scores 0.70, 0.75, 0.72, 0.95, 0.68. One fold is very different. What might cause that, and what would you check?
- Change the from-scratch code to 10 folds. Does the mean change much? What about the standard deviation of fold scores, and why?
- In the scikit-learn code, widen the grid to
[0.0001, 0.001, 0.01, 0.1, 1, 10, 100, 1000]and printinner.fit(X, y).best_score_alongside the nested score. Which is higher?Hint for 1: the mean is 0.76. An outlying fold often means the shuffle put an unusual subgroup (one hospital, one time period, duplicates) into it.
Learn more
Hand-picked courses, books, videos and tutorials for going deeper. See all resources →
MLU-Explain: Cross-Validation
An animated explainer of k-fold, leave-one-out and other cross-validation schemes.
scikit-learn: Cross-validation: evaluating estimator performance
The reference for every splitter in scikit-learn (KFold, StratifiedKFold, GroupKFold, TimeSeriesSplit and more), with diagrams of how each one cuts the data.
An Introduction to Statistical Learning (with Python)
The friendliest rigorous introduction to classical ML, with Python labs. Free PDF.
StatQuest
Short, cheerful, very clear videos on statistics and nearly every ML algorithm.
On Over-fitting in Model Selection and Subsequent Selection Bias in Performance Evaluation
Shows that tuning hyperparameters on the same data used to report performance can bias results as much as the differences between algorithms, and argues for nested cross-validation.
The Elements of Statistical Learning
The graduate-level reference for classical statistical learning. Free PDF.
Facts checked as of 30 November 2026. Fast-moving details (products, prices, laws) change often. · Source: content/entries/ml/cross-validation.md