Sign in

Cross validation

Cross-validation strategies

Cross-validation strategies for tuning: k-fold, stratified, group, time series, leave-one-out, repeated and Monte Carlo splits, with scoring and model selection.

Overview

To choose between models you need to know how each does on data it has not seen. Cross-validation finds out by rotation: split the data into parts, hold one part back, fit on the rest, score on the held-back part, and repeat until every part has had its turn. How you cut the parts must match how the model will be used. If it will meet new customers, no customer may appear on both sides. If it will predict the future, it may only be tested on rows that come later than its training rows.

A short history

Mervyn Stone in 1974 and Seymour Geisser in 1975 formalised cross-validation for choosing and assessing statistical predictions. Leave-one-out is the oldest form, and k-fold became the practical default as datasets grew. Stratified, grouped and time-ordered variants were added to respect the structure of real data. Gavin Cawley and Nicola Talbot showed in 2010 that the score of the selected model is optimistic, which is why a separate test set or nested cross-validation is used for the final estimate.

How it works

  1. Choose a strategy that matches the data: kfold, stratified, group, time_series, leave_one_out, repeated or monte_carlo.
  2. split returns the pairs of training and test indices. Stratified keeps class shares, group keeps each group on one side, time_series only tests on later rows.
  3. cross_val_score runs a fit_predict(X_train, y_train, X_test) function on every pair and scores its predictions.
  4. select scores several candidates on the same splits and records the mean, standard deviation and standard error of each.
  5. It returns the candidate with the best mean, or, with one_standard_error, the first candidate whose mean is within one standard error of the best.
  6. Refit the chosen candidate on all the training data and check it once on a separate test set.

Watch out for

  • Plain k-fold on grouped data puts rows of the same customer or patient on both sides, so the model is tested on entities it already knows and the score is too high.
  • Plain k-fold on time-ordered data trains on the future. Use the time_series strategy, with a gap if features look back in time.
  • The score of the selected candidate is biased upward, because it was chosen for being the highest. Keep a test set the selection never sees.
  • Leave-one-out fits one model per row, which is expensive, and its scores are strongly related to each other because the training sets are almost identical.
  • The one-standard-error rule takes the first qualifying candidate in the order you supply, so the candidates must be listed from simplest to most complex.

Use cases

When to use it

When choosing between models or hyperparameter values. Use stratified for imbalanced classes, group when rows of one entity are related, time_series when the model will predict the future, and leave_one_out for a few dozen rows.

In industry

Medical research
Several scans or visits come from one patient. Group cross-validation keeps each patient on one side of the split, so the model is tested on people it has never seen.
Finance and energy forecasting
Time series splits train on the past and test on the following period, repeated over expanding windows, to choose a forecasting model honestly.
Fraud and rare events
Stratified folds keep the small share of positive cases equal across folds, so candidate models are compared on the same footing.

Choosing it: what must hold

  • Several candidate models or hyperparameter values to choose between.
  • A split strategy that matches how the model will meet new data: by row, by group or forward in time.
  • All candidates scored on the same splits.
  • A final test set kept outside the selection, because the winning score is optimistic.

When to choose something else

IfUse instead
Data is plentiful and one training run is expensiveA single train, validation and test split from the data splitting lesson
You only want a performance estimate for one fixed modelThe holdout and cross-validation evaluation lesson
The candidates are too many to list by handThe hyperparameter optimization lesson, with cross-validation as its objective

Math foundations

  1. The cross-validation score

    sˉ=1K∑k=1Ksk\bar{s} = \frac{1}{K} \sum_{k=1}^{K} s_k

    The mean of the scores over the KK splits. It is the number each candidate is judged by.

  2. Standard error of that mean

    SE⁡=σ^K,σ^=1K−1∑k=1K(sk−sˉ)2\operatorname{SE} = \frac{\hat{\sigma}}{\sqrt{K}}, \qquad \hat{\sigma} = \sqrt{\frac{1}{K - 1} \sum_{k=1}^{K} (s_k - \bar{s})^2}

    How uncertain the mean is, given the spread of the split scores. Differences between candidates that are smaller than this are not reliable.

  3. The one-standard-error rule

    choose the simplest candidate c with sˉc≤sˉbest+SE⁡best(lower is better)\text{choose the simplest candidate } c \text{ with } \bar{s}_c \le \bar{s}_{\text{best}} + \operatorname{SE}_{\text{best}} \qquad (\text{lower is better})

    When several candidates are within noise of the best, prefer the simplest. A simpler model is less likely to owe its score to luck on these splits.

  4. Group constraint

    groups⁡(Tk) ∩ groups⁡(Vk)=∅for every split k\operatorname{groups}(T_k) \,\cap\, \operatorname{groups}(V_k) = \varnothing \quad \text{for every split } k

    With the group strategy no group has rows on both sides of a split. The test score then measures performance on entities never seen in training.

  5. Time series splits

    m=⌊nK+1⌋,ak=n−(K−k) m,Vk=[ ak,  ak+m ),Tk=[ bk,  ak−g )m = \left\lfloor \frac{n}{K + 1} \right\rfloor, \qquad a_k = n - (K - k)\,m, \qquad V_k = [\,a_k,\; a_k + m\,), \qquad T_k = [\,b_k,\; a_k - g\,)

    With splits numbered k=0,…,K−1k = 0, \dots, K - 1, each tests on one block of mm rows and trains only on rows that end gg before it. The training window starts at bk=0b_k = 0 (expanding window), or keeps only the most recent max_train_size rows (rolling window).

  6. Cost in model fits

    #fits=(candidates)×(splits),splits=K,    n  (leave-one-out),    K⋅R  (repeated)\#\text{fits} = (\text{candidates}) \times (\text{splits}), \qquad \text{splits} = K,\;\; n \;(\text{leave-one-out}),\;\; K \cdot R \;(\text{repeated})

    Every candidate is fitted once per split. This is the budget to check before choosing a strategy.

Symbols

sks_k
score on split k
KK
n_splits
sˉ\bar{s}
mean score of a candidate
σ^\hat{\sigma}
sample standard deviation of the split scores
SE⁡\operatorname{SE}
standard error of the mean score
Tk, VkT_k,\, V_k
training and test index sets of split k
cc
one candidate model
mm
block length of the time series splits
ak, bka_k,\, b_k
first test row and first training row of time series split k
gg
gap between training and test rows
nn
number of rows
RR
n_repeats

Worked by hand

Three polynomial models are scored by 5-fold MSE, listed from simplest to most complex. Degree 1: mean 0.050. Degree 3: mean 0.020. Degree 9: mean 0.018 with standard error 0.005.

sˉbest=min⁡(0.050,  0.020,  0.018)=0.018(degree 9)\bar{s}_{\text{best}} = \min(0.050,\; 0.020,\; 0.018) = 0.018 \quad (\text{degree } 9)
sˉbest+SE⁡best=0.018+0.005=0.023\bar{s}_{\text{best}} + \operatorname{SE}_{\text{best}} = 0.018 + 0.005 = 0.023
0.050>0.023,0.020≤0.023  ⇒  degree 30.050 > 0.023, \qquad 0.020 \le 0.023 \;\Rightarrow\; \text{degree } 3
#fits=3×5=15\#\text{fits} = 3 \times 5 = 15

Degree 9 has the lowest mean, but degree 3 is within one standard error of it and simpler, so the rule picks degree 3. Without the rule select returns degree 9.

Visual example

Loading the example.

Try this

  • Press Next split and watch the test fold rotate through the rows.
  • Switch the strategy from kfold to group: whole groups now move together, and the high degrees stop looking so good.
  • Choose group or time_series and turn one_standard_error on: the choice moves from degree 3 to degree 1, which sits inside the band.

Code sample

import numpy as np
from impl import CrossValidator
from config import CrossValidationConfig

rng = np.random.default_rng(0)
x = rng.uniform(-1, 1, size=60)
y = x**3 - x + 0.05 * rng.normal(size=60)

def poly(degree):
    return lambda x_train, y_train, x_test: np.polyval(np.polyfit(x_train, y_train, degree), x_test)

mse = lambda y_true, y_pred: float(((y_true - y_pred) ** 2).mean())
cv = CrossValidator(CrossValidationConfig(strategy="kfold", n_splits=5))
best, table = cv.select({"degree 1": poly(1), "degree 3": poly(3), "degree 9": poly(9)}, x, y, mse)
print(best, {name: round(row["mean"], 4) for name, row in table.items()})   # degree 3
Read the implementation (153 lines)
"""Cross-validation strategies for model selection: k-fold, stratified, group, time series, leave-one-out,
repeated and Monte Carlo splits, plus scoring and choosing between candidates on those splits.

NumPy only. `split` returns (train_indices, test_indices) pairs. `cross_val_score` runs a
`fit_predict(X_train, y_train, X_test) -> predictions` function over them, and `select` picks the best of
several candidates, optionally with the one-standard-error rule.
"""
from __future__ import annotations

from typing import Callable

import numpy as np

try:
    from .config import CrossValidationConfig
except ImportError:  # run from the template's own folder
    from config import CrossValidationConfig


def _pairs_from_fold_ids(fold_of: np.ndarray, n_splits: int) -> list[tuple[np.ndarray, np.ndarray]]:
    """Turn 'row i belongs to fold fold_of[i]' into (train, test) index pairs."""
    rows = np.arange(len(fold_of))
    return [(rows[fold_of != k], rows[fold_of == k]) for k in range(n_splits)]


class CrossValidator:
    """Build cross-validation splits and use them to score and select models."""

    def __init__(self, config: CrossValidationConfig | None = None) -> None:
        self.config = config or CrossValidationConfig()

    # --------------------------------------------------------------------------------------- strategies
    def _kfold(self, n: int, rng: np.random.Generator, shuffle: bool) -> list:
        k = self.config.n_splits
        order = rng.permutation(n) if shuffle else np.arange(n)
        fold_of = np.empty(n, dtype=int)
        fold_of[order] = np.arange(n) * k // n          # consecutive blocks of the (shuffled) order
        return _pairs_from_fold_ids(fold_of, k)

    def _stratified(self, y: np.ndarray, rng: np.random.Generator) -> list:
        k = self.config.n_splits
        fold_of = np.empty(len(y), dtype=int)
        offset = 0
        for label in np.unique(y):
            members = np.flatnonzero(y == label)
            if len(members) < k:
                raise ValueError(f"class {label!r} has {len(members)} rows, fewer than n_splits={k}")
            if self.config.shuffle:
                members = rng.permutation(members)
            fold_of[members] = (offset + np.arange(len(members))) % k   # deal the class out like cards
            offset += len(members)
        return _pairs_from_fold_ids(fold_of, k)

    def _group(self, groups: np.ndarray) -> list:
        k = self.config.n_splits
        names, inverse, sizes = np.unique(groups, return_inverse=True, return_counts=True)
        if len(names) < k:
            raise ValueError(f"{len(names)} groups cannot fill {k} folds")
        fold_sizes = np.zeros(k, dtype=int)
        fold_of_group = np.empty(len(names), dtype=int)
        for g in np.argsort(-sizes, kind="stable"):     # largest group first, into the emptiest fold
            target = int(fold_sizes.argmin())
            fold_of_group[g] = target
            fold_sizes[target] += sizes[g]
        return _pairs_from_fold_ids(fold_of_group[inverse], k)

    def _time_series(self, n: int) -> list:
        cfg = self.config
        block = n // (cfg.n_splits + 1)
        if block < 1:
            raise ValueError(f"{n} rows are too few for {cfg.n_splits} time series splits")
        pairs = []
        for k in range(cfg.n_splits):
            test_start = n - (cfg.n_splits - k) * block
            train_end = test_start - cfg.gap
            train_start = max(0, train_end - cfg.max_train_size) if cfg.max_train_size else 0
            if train_end - train_start < 1:
                raise ValueError(f"gap={cfg.gap} leaves no training rows for split {k}")
            pairs.append((np.arange(train_start, train_end), np.arange(test_start, test_start + block)))
        return pairs

    def split(self, n: int, y=None, groups=None) -> list[tuple[np.ndarray, np.ndarray]]:
        """The (train_indices, test_indices) pairs for n rows.

        y:      labels of shape (n,), needed by "stratified".
        groups: group id per row, shape (n,), needed by "group" (for example the patient or user of a row).
        """
        cfg = self.config
        rng = np.random.default_rng(cfg.seed)
        if cfg.strategy == "leave_one_out":
            rows = np.arange(n)
            return [(np.delete(rows, i), rows[i: i + 1]) for i in range(n)]
        if cfg.strategy == "time_series":
            return self._time_series(n)
        if cfg.strategy == "monte_carlo":
            n_test = max(1, int(round(n * cfg.test_fraction)))
            if n_test >= n:
                raise ValueError(f"{n} rows are too few for test_fraction={cfg.test_fraction}")
            pairs = []
            for _ in range(cfg.n_splits):
                order = rng.permutation(n)
                pairs.append((np.sort(order[n_test:]), np.sort(order[:n_test])))
            return pairs
        if n < cfg.n_splits:
            raise ValueError(f"cannot make {cfg.n_splits} folds from {n} rows")
        if cfg.strategy == "stratified":
            if y is None:
                raise ValueError('strategy "stratified" needs y')
            return self._stratified(np.asarray(y), rng)
        if cfg.strategy == "group":
            if groups is None:
                raise ValueError('strategy "group" needs groups')
            return self._group(np.asarray(groups))
        if cfg.strategy == "repeated":
            return [pair for _ in range(cfg.n_repeats) for pair in self._kfold(n, rng, shuffle=True)]
        return self._kfold(n, rng, cfg.shuffle)

    # ------------------------------------------------------------------------------- scoring / selecting
    def cross_val_score(self, fit_predict: Callable, X, y, score: Callable, groups=None) -> np.ndarray:
        """Score one candidate on every split.

        fit_predict: function(X_train, y_train, X_test) -> predictions for X_test.
        score:       function(y_true, y_pred) -> float.
        X: shape (n, ...). y: shape (n,). Returns the scores, shape (n_splits,).
        """
        X, y = np.asarray(X), np.asarray(y)
        scores = []
        for train, test in self.split(len(y), y=y, groups=groups):
            scores.append(float(score(y[test], fit_predict(X[train], y[train], X[test]))))
        return np.array(scores)

    def select(self, candidates: dict, X, y, score: Callable, higher_is_better: bool = False,
               groups=None, one_standard_error: bool = False) -> tuple[str, dict]:
        """Score every candidate on the same splits and choose one.

        candidates: {name: fit_predict function}. Order them from simplest to most complex when
                    one_standard_error is used.
        one_standard_error: instead of the best mean, take the FIRST candidate whose mean is within one
                    standard error of the best. This prefers the simpler model when the difference is noise.
        Returns (chosen name, {name: {"mean", "std", "stderr", "scores"}}).
        """
        table = {}
        for name, fit_predict in candidates.items():
            scores = self.cross_val_score(fit_predict, X, y, score, groups)
            std = float(scores.std(ddof=1)) if len(scores) > 1 else 0.0
            table[name] = {"mean": float(scores.mean()), "std": std, "stderr": std / np.sqrt(len(scores)),
                           "scores": scores}
        sign = 1.0 if higher_is_better else -1.0
        best = max(table, key=lambda name: sign * table[name]["mean"])
        if one_standard_error:
            threshold = sign * table[best]["mean"] - table[best]["stderr"]
            best = next(name for name in table if sign * table[name]["mean"] >= threshold)
        return best, table
Repository
Not published yet
Needs
Python 3.10 and NumPy
Tests
9, run with python3 -m unittest -v

Practice

Make 60 rows where each of 12 users contributes 5 rows that share a user-specific offset. Call CrossValidator(CrossValidationConfig(strategy=s, n_splits=4)).cross_val_score(fit_predict, X, y, score, groups=users) for kfold and for group with a nearest-neighbour fit_predict. Compare the scores and explain the gap.

Check on learning

  1. A medical dataset has 20 scans per patient. Plain 5-fold gives 97 percent accuracy and group 5-fold gives 81 percent. Which number describes what the hospital will see, and why is the other so high?
    A way to think about it

    With plain folds, scans of one patient sit on both sides. Ask what the model can recognise besides the disease.

  2. Two candidates have mean errors 0.200 and 0.198, each with a standard error of 0.010. Is the second one better?
    A way to think about it

    Compare the difference between the means with the uncertainty of each mean. Then ask what else could break the tie.

  3. Why does the one-standard-error rule lean toward the simpler model instead of the one with the best mean?
    A way to think about it

    The best mean is partly luck. Think about which kind of model is more likely to have gained from luck on five particular splits.

  4. Leave-one-out uses almost all the data for every fit. Why is it not always the best choice?
    A way to think about it

    Count the fits for 10,000 rows. Then ask how different two of its training sets are and what that does to the spread of the scores.

  5. After picking the best of 40 candidates by cross-validation you report its cross-validation score as the expected performance. What is wrong, and what would you do instead?
    A way to think about it

    The maximum of many noisy estimates overshoots. Think of a set of rows that took no part in the choice.