◆ AI All-in-One

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
↗ Plan a path here

Read first

Training, Validation and Test Sets

This leads to

Hyperparameter Tuning
The full path from zero — 5 concepts before this one
  1. What Is AI?
  2. How Machines Learn
  3. Supervised, Unsupervised and Reinforcement Learning
  4. Supervised Learning
  5. Training, Validation and Test Sets
  6. 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.

The data, shuffled and cut into 5 folds fold 1 fold 2 fold 3 fold 4 fold 5 Round 1 validate train train train train accuracy 0.982 Round 2 train validate train train train accuracy 0.965 Round 3 train train validate train train accuracy 1.000 Round 4 train train train validate train accuracy 0.974 Round 5 train train train train validate accuracy 0.965 mean 0.977 spread ± 0.013 Every example is used for validation exactly once and for training four times. A fresh model is fitted each round.
Fig. 1 5-fold cross-validation. The data is cut into five folds. In each round a fresh model trains on four folds and is scored on the fifth. Every example is validated exactly once. The five scores (real numbers from the code below) are averaged.

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 kk folds, train kk times, each time validating on a different fold, and average the kk 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

  1. Shuffle the examples (unless their order matters; see time series below).
  2. Split them into kk folds of roughly equal size. Common choices are k=5k = 5 or k=10k = 10.
  3. For i=1,…,ki = 1, \dots, k: train a fresh model on all folds except fold ii, and compute its score sis_i on fold ii.
  4. Report the mean sˉ=1k∑i=1ksi\bar{s} = \frac{1}{k}\sum_{i=1}^{k} s_i and the standard deviation of the sis_i.

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: (0.92+0.88+0.95+0.90+0.85)/5=4.50/5=0.90(0.92 + 0.88 + 0.95 + 0.90 + 0.85) / 5 = 4.50 / 5 = 0.90.
  • Deviations from the mean: +0.02,−0.02,+0.05,0,−0.05+0.02, -0.02, +0.05, 0, -0.05. Squared: 0.0004,0.0004,0.0025,0,0.00250.0004, 0.0004, 0.0025, 0, 0.0025. Their average is 0.0058/5=0.001160.0058 / 5 = 0.00116, and its square root is the standard deviation, 0.0340.034.
  • So the result is about 0.90±0.030.90 \pm 0.03.

How should you read that ±0.03? It is the spread of individual fold scores. The uncertainty of the mean is smaller, roughly 0.034/5≈0.0150.034 / \sqrt{5} \approx 0.015. 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?

  • k=5k = 5 or 1010 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 kk 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 NN 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.
0.94 0.95 0.96 0.97 0.98 0.99 1.00 accuracy 20 single 80/20 splits 0.947 to 0.991 20 runs of 5-fold CV 0.974 to 0.979 Same model, same data, different random shuffles. One split is a noisy estimate; the average over 5 folds is far steadier.
Fig. 2 The same model evaluated 20 times on single 80/20 splits (red) and 20 times with 5-fold cross-validation (green), each time with a different random shuffle. Single splits range from 0.947 to 0.991; cross-validated estimates stay between 0.974 and 0.979.

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.

Outer loop: estimate how well the whole procedure works train test train train train outer round 2 of 5: fold 2 is held out and not touched until the end Inner loop on the 4 training folds only: pick the best setting (e.g. C) by cross-validation val train train train train val train train train train val train train train train val best C = 0.1 (say) refit on all 4 training folds score once on outer fold 2 an honest estimate for this round Repeat for all 5 outer folds and average the 5 outer scores. The tuning never saw the fold it is scored on, so the average measures "tune, then train" as a whole, without optimism.
Fig. 3 Nested cross-validation. Each outer round holds out one fold. The inner loop runs its own cross-validation on the remaining folds to choose the hyperparameter, refits with that choice, and only then scores once on the held-out outer fold.

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 kk. 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 Pipeline and 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 GroupKFold or TimeSeriesSplit. 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

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

  1. 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?
  2. Change the from-scratch code to 10 folds. Does the mean change much? What about the standard deviation of fold scores, and why?
  3. In the scikit-learn code, widen the grid to [0.0001, 0.001, 0.01, 0.1, 1, 10, 100, 1000] and print inner.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.

Check your understanding

5 quick questions. Pick an answer to see whether you were right and why. Your best score is saved on this device.

  1. A model scores 0.92, 0.88, 0.95, 0.90 and 0.85 on five folds. A second model averages 0.91 on the same folds. What should you conclude?

  2. You standardise the whole dataset, then run 5-fold cross-validation. What is wrong?

  3. You have several scans per patient, and the model will be used on new patients. Which scheme should you use?

  4. You try 20 hyperparameter values with 5-fold CV and report the best average score as your final result. What is the problem?

  5. For a model forecasting next month's sales from daily data, which validation scheme is right?

Finished this chapter?

Learn more

Hand-picked courses, books, videos and tutorials for going deeper. See all resources →

Interactive

MLU-Explain: Cross-Validation

Amazon Machine Learning University (MLU-Explain) · Beginner · Free

An animated explainer of k-fold, leave-one-out and other cross-validation schemes.

Video

StatQuest

Josh Starmer · Beginner · Free

Short, cheerful, very clear videos on statistics and nearly every ML algorithm.

Facts checked as of 30 November 2026. Fast-moving details (products, prices, laws) change often. · Source: content/entries/ml/cross-validation.md