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
- Decide the shares with
val_fractionandtest_fraction. The rest is training data. train_val_testshuffles the row indices with a seed and cuts them into three disjoint parts.- With
stratify, each class is split separately with the same fractions, so every part keeps the class proportions. time_splitkeeps the order: oldest rows train, the newest rows test, withgaprows left unused at each boundary.kfoldassigns every row to one ofn_splitsfolds. Each fold is the validation part once while the others train.time_series_foldsgives 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
| If | Use instead |
|---|---|
| Several rows belong to one person, device or session | The group strategy in the cross-validation strategies lesson |
| You want a score with a spread, not only index sets | The holdout and cross-validation evaluation lesson |
| Rows are ordered in time | The time split or expanding-window folds of this lesson, never a random shuffle |
Math foundations
Part sizes
The three parts are disjoint and together cover every row. The fractions must sum to less than 1 so that training rows remain.
Stratification keeps class shares
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.
K-fold sizes
Every row is in exactly one validation fold. Each model trains on about of the data and all rows are used for validation once.
Expanding-window folds
With folds numbered , the rows are cut into blocks of . Fold validates on one block and trains on all earlier rows, less a gap of . Training rows always come before validation rows.
Symbols
- number of rows
- val_fraction and test_fraction
- number of rows of class c
- n_splits, the number of folds
- validation and training index sets of fold k
- block length of the time folds
- first validation row of fold k
- gap, rows left out between training and validation
Worked by hand
Split rows with both fractions 0.2. Then build time-series folds for the same 100 rows with and no gap.
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 startsRead 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
- 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.
- 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 . Then ask what recall means with zero positives.
- 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.
- 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.
- 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.