Sign in

Splitting

Data splitting: train, validation and test sets

A splitter that divides row indices into train, validation and test parts: random, stratified, time-ordered, k-fold and expanding-window folds.

Overview

A model that is scored on the rows it learned from will look better than it is, the way a student looks good on an exam they have already seen. Splitting sets rows aside before any learning. The training part is for fitting, the validation part is for making choices such as settings and model type, and the test part is opened once at the end for an honest final number. How you cut matters: classes should keep their proportions, and with time-ordered data the test rows must come after the training rows.

A short history

Holding data back to test a model is an old statistical idea. Mervyn Stone in 1974 and Seymour Geisser in 1975 gave cross-validation its formal treatment as a way to judge predictions on data not used for fitting. The three way split into training, validation and test sets became routine in machine learning as models gained many settings to tune. Splits ordered by time come from forecasting practice, where testing on the past of the training data would be cheating.

How it works

  1. Decide the shares with val_fraction and test_fraction. The rest is training data.
  2. train_val_test shuffles the row indices with a seed and cuts them into three disjoint parts.
  3. With stratify, each class is split separately with the same fractions, so every part keeps the class proportions.
  4. time_split keeps the order: oldest rows train, the newest rows test, with gap rows left unused at each boundary.
  5. kfold assigns every row to one of n_splits folds. Each fold is the validation part once while the others train.
  6. time_series_folds gives expanding-window folds: each fold trains on everything before a block and validates on that block.

Watch out for

  • A random split of time-ordered data lets the model train on the future and be tested on the past, so the score is far better than anything it can reach live.
  • Fitting a scaler or encoder before splitting leaks test information into training, because the fitted numbers already contain the test rows.
  • Sizes are rounded to whole rows, so a small class or a small fraction can round to zero and leave a part without any row of that class.
  • Rows that belong together, such as several rows from one customer, can land on both sides of a random split and make the test look easier than new customers will be.
  • Choosing settings by looking at the test part again and again turns it into a second validation set, and its score stops being an honest estimate.

Use cases

When to use it

Before any fitting, including the fitting of scalers and encoders. Use the stratified variants for rare classes, the time-based ones for rows ordered in time, and k-fold when the data is too small for a fixed validation set.

In industry

Medical diagnosis
A disease may appear in a few percent of patients. A stratified split keeps that share in every part, so the test set is not left with almost no positive cases.
Finance and forecasting
A price or demand model is trained on older months and tested on the newest ones, with a gap between them, which mirrors how it will be used.
Small research datasets
With a few hundred rows a single validation set is too noisy, so k-fold splitting lets every row serve once for validation.

Choosing it: what must hold

  • The split is made before anything is fitted, including scalers and encoders.
  • Rows that are independent of each other for a random split. Related rows must stay on one side.
  • Enough rows that the validation and test parts give a stable estimate.
  • A test part that is used once, at the end, and not for tuning.

When to choose something else

IfUse instead
Several rows belong to one person, device or sessionThe group strategy in the cross-validation strategies lesson
You want a score with a spread, not only index setsThe holdout and cross-validation evaluation lesson
Rows are ordered in timeThe time split or expanding-window folds of this lesson, never a random shuffle

Math foundations

  1. Part sizes

    ntest=round⁡(n ftest),nval=round⁡(n fval),ntrain=n−nval−ntestn_{\text{test}} = \operatorname{round}(n\, f_{\text{test}}), \qquad n_{\text{val}} = \operatorname{round}(n\, f_{\text{val}}), \qquad n_{\text{train}} = n - n_{\text{val}} - n_{\text{test}}

    The three parts are disjoint and together cover every row. The fractions must sum to less than 1 so that training rows remain.

  2. Stratification keeps class shares

    nc, partnpart≈ncnfor every class c and every part\frac{n_{c,\,\text{part}}}{n_{\text{part}}} \approx \frac{n_c}{n} \quad \text{for every class } c \text{ and every part}

    Each class is split on its own with the same fractions, so its share in train, validation and test matches its share overall, up to rounding.

  3. K-fold sizes

    ∣Vk∣≈nK,∣Tk∣≈(K−1) nK,⋃k=1KVk={1,…,n}|V_k| \approx \frac{n}{K}, \qquad |T_k| \approx \frac{(K - 1)\,n}{K}, \qquad \bigcup_{k=1}^{K} V_k = \{1, \dots, n\}

    Every row is in exactly one validation fold. Each model trains on about (K−1)/K(K-1)/K of the data and all rows are used for validation once.

  4. Expanding-window folds

    m=⌊nK+1⌋,Vk=[ sk,  sk+m ),Tk=[ 0,  sk−g ),sk=n−(K−k) mm = \left\lfloor \frac{n}{K + 1} \right\rfloor, \qquad V_k = [\,s_k,\; s_k + m\,), \qquad T_k = [\,0,\; s_k - g\,), \qquad s_k = n - (K - k)\,m

    With folds numbered k=0,…,K−1k = 0, \dots, K - 1, the rows are cut into blocks of mm. Fold kk validates on one block and trains on all earlier rows, less a gap of gg. Training rows always come before validation rows.

Symbols

nn
number of rows
fval, ftestf_{\text{val}},\, f_{\text{test}}
val_fraction and test_fraction
ncn_c
number of rows of class c
KK
n_splits, the number of folds
Vk, TkV_k,\, T_k
validation and training index sets of fold k
mm
block length of the time folds
sks_k
first validation row of fold k
gg
gap, rows left out between training and validation

Worked by hand

Split n=100n = 100 rows with both fractions 0.2. Then build time-series folds for the same 100 rows with K=4K = 4 and no gap.

ntest=round⁡(100×0.2)=20,nval=20,ntrain=100−20−20=60n_{\text{test}} = \operatorname{round}(100 \times 0.2) = 20, \qquad n_{\text{val}} = 20, \qquad n_{\text{train}} = 100 - 20 - 20 = 60
m=⌊1004+1⌋=20m = \left\lfloor \frac{100}{4 + 1} \right\rfloor = 20
k=0:s0=100−4×20=20,T0=[0,20),V0=[20,40)k = 0: \quad s_0 = 100 - 4 \times 20 = 20, \qquad T_0 = [0, 20), \qquad V_0 = [20, 40)
k=3:s3=100−1×20=80,T3=[0,80),V3=[80,100)k = 3: \quad s_3 = 100 - 1 \times 20 = 80, \qquad T_3 = [0, 80), \qquad V_3 = [80, 100)

The random split gives 60, 20 and 20 rows. The time folds train on 20, 40, 60 and 80 rows in turn, each validating on the 20 rows that follow.

Visual example

Loading the example.

Try this

  • Click each of the four splitters at the bottom of the tree and compare the strips.
  • On train_val_test, turn stratify on and compare the share of marked rows in each part.
  • On time_series_folds, raise the gap and watch unused rows open up before each validation block.

Code sample

import numpy as np
from impl import Splitter
from config import SplittingConfig

y = np.array([0] * 80 + [1] * 20)
splitter = Splitter(SplittingConfig(val_fraction=0.2, test_fraction=0.2, stratify=True, seed=0))
train, val, test = splitter.train_val_test(len(y), y)
print(len(train), len(val), len(test), y[test].mean())    # 60 20 20 0.2

for train_idx, val_idx in Splitter(SplittingConfig(n_splits=4)).time_series_folds(100):
    print(train_idx[-1], val_idx[0], val_idx[-1])          # training always ends before validation starts
Read the implementation (117 lines)
"""Data splitting: random or stratified train/val/test, time-ordered split, k-fold, expanding-window folds.

NumPy only. Every method returns arrays of row indices, never copies of the data, so the same split can be
applied to features, labels and any side table.
"""
from __future__ import annotations

import numpy as np

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


class Splitter:
    """Produce index sets for the usual ways of splitting n rows."""

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

    # ------------------------------------------------------------------------------------------ helpers
    def _order(self, indices: np.ndarray, rng: np.random.Generator) -> np.ndarray:
        """The indices, shuffled when the config says so."""
        return rng.permutation(indices) if self.config.shuffle else indices

    def _labels(self, n: int, y) -> np.ndarray:
        if y is None:
            raise ValueError("stratify needs the labels y")
        y = np.asarray(y)
        if y.shape[0] != n:
            raise ValueError(f"y has {y.shape[0]} rows, expected {n}")
        return y

    # ------------------------------------------------------------------------------- train / val / test
    def train_val_test(self, n: int, y=None) -> tuple[np.ndarray, np.ndarray, np.ndarray]:
        """Split range(n) into three disjoint index arrays (train, val, test).

        n: number of rows. y: labels of shape (n,), used only when stratify is on.
        With stratify, each class is split separately with the same fractions, so every part keeps the
        class proportions (up to rounding).
        """
        cfg = self.config
        rng = np.random.default_rng(cfg.seed)
        if cfg.stratify:
            y = self._labels(n, y)
            groups = [np.flatnonzero(y == label) for label in np.unique(y)]
        else:
            groups = [np.arange(n)]
        train, val, test = [], [], []
        for group in groups:
            group = self._order(group, rng)
            n_test = int(round(len(group) * cfg.test_fraction))
            n_val = int(round(len(group) * cfg.val_fraction))
            test.append(group[:n_test])
            val.append(group[n_test: n_test + n_val])
            train.append(group[n_test + n_val:])
        parts = [np.concatenate(part) for part in (train, val, test)]
        if cfg.stratify:  # put the classes back in a mixed (or original) order
            parts = [self._order(np.sort(part), rng) for part in parts]
        return parts[0], parts[1], parts[2]

    def time_split(self, n: int) -> tuple[np.ndarray, np.ndarray, np.ndarray]:
        """Ordered split for rows sorted by time: oldest rows train, then val, newest rows test.

        `gap` rows are left out before val and before test. Returns (train, val, test) index arrays.
        """
        cfg = self.config
        n_test = int(round(n * cfg.test_fraction))
        n_val = int(round(n * cfg.val_fraction))
        test_start = n - n_test
        val_end = test_start - (cfg.gap if n_test else 0)
        val_start = val_end - n_val
        train_end = val_start - (cfg.gap if n_val else 0)
        if train_end <= 0:
            raise ValueError(f"no rows left for training with n={n}, gap={cfg.gap}")
        return np.arange(train_end), np.arange(val_start, val_end), np.arange(test_start, n)

    # --------------------------------------------------------------------------------------------- folds
    def kfold(self, n: int, y=None) -> list[tuple[np.ndarray, np.ndarray]]:
        """n_splits pairs (train_indices, val_indices). Every row is in exactly one validation fold.

        With stratify, the rows of each class are dealt out to the folds in turn, so each fold holds
        the same number of rows of a class, give or take one.
        """
        cfg = self.config
        if n < cfg.n_splits:
            raise ValueError(f"cannot make {cfg.n_splits} folds from {n} rows")
        rng = np.random.default_rng(cfg.seed)
        fold_of = np.empty(n, dtype=int)
        if cfg.stratify:
            y = self._labels(n, y)
            start = 0
            for label in np.unique(y):
                members = self._order(np.flatnonzero(y == label), rng)
                fold_of[members] = (start + np.arange(len(members))) % cfg.n_splits
                start += len(members)  # continue where the last class stopped so fold sizes stay even
        else:
            fold_of[self._order(np.arange(n), rng)] = np.arange(n) * cfg.n_splits // n
        everything = np.arange(n)
        return [(everything[fold_of != k], everything[fold_of == k]) for k in range(cfg.n_splits)]

    def time_series_folds(self, n: int) -> list[tuple[np.ndarray, np.ndarray]]:
        """Expanding-window folds for time-ordered rows.

        The rows are cut into n_splits + 1 blocks. Fold k trains on everything before block k + 1 (minus
        `gap` rows) and validates on block k + 1, so validation rows are always later than training rows.
        """
        cfg = self.config
        block = n // (cfg.n_splits + 1)
        if block < 1 or n - cfg.n_splits * block - cfg.gap < 1:
            raise ValueError(f"too few rows ({n}) for {cfg.n_splits} time folds with gap {cfg.gap}")
        folds = []
        for k in range(cfg.n_splits):
            val_start = n - (cfg.n_splits - k) * block
            folds.append((np.arange(val_start - cfg.gap), np.arange(val_start, val_start + block)))
        return folds
Repository
Not published yet
Needs
Python 3.10 and NumPy
Tests
8, run with python3 -m unittest -v

Practice

With y = np.array([0] * 95 + [1] * 5), call Splitter(SplittingConfig(val_fraction=0.2, test_fraction=0.2, seed=0)).train_val_test(100, y) with stratify off and on. Count the rows of class 1 in each part both times. Then run time_series_folds(100) with gap=5 and print the last training index and the first validation index of each fold.

Check on learning

  1. Daily sales are split at random into train and test. The model scores very well, then fails in production. Explain the mechanism.
    A way to think about it

    For a test day in the middle of the data, list which nearby days are in the training set. Ask how hard it is to guess a day when you know the day before and the day after.

  2. A class makes up 1 percent of 300 rows. Without stratification, how likely is it that the 30-row test part contains no row of that class, and what happens to recall then?
    A way to think about it

    There are 3 such rows. Estimate the chance that all three miss the test part, about 0.930.9^3. Then ask what recall means with zero positives.

  3. Why is a gap useful in a time split when features include a 7-day rolling mean?
    A way to think about it

    Take the first validation row and list which days enter its rolling mean. Check whether any of those days are also training targets.

  4. With 5 folds each model trains on 80 percent of the data, with 10 folds on 90 percent. What do you gain and what do you pay by using more folds?
    A way to think about it

    Compare the size of each training set with the full data, the number of models to fit, and the number of rows each validation score is based on.

  5. You tune 50 settings against the validation set and report the best validation score as the model's performance. Why is that number too optimistic?
    A way to think about it

    Each score is the true quality plus noise. Think about what you get when you take the best of 50 noisy numbers, and what the test part is for.