Overview
A model can score well on the rows it was trained on simply by memorising them. To learn how it will do on new data, you hold some rows back and test on those. Three parts are usual. The training part fits the model. The validation part is used to choose between settings. The test part is opened once at the end, for an honest final number. The method returns row indices, not copies of the data, so the same split can be applied to the features, the labels and anything else that shares the row order.
A short history
Holding back data to check a model is an old idea in statistics. Cross-validation was put on a formal footing by Mervyn Stone in 1974 and Seymour Geisser in 1975. The three-way split into training, validation and test sets became standard in machine learning as models gained hyperparameters to tune, and public benchmarks with fixed test sets made it the common way to compare methods.
How it works
- Set the three fractions so they sum to 1, for example 0.7, 0.15 and 0.15.
- If shuffle is on, the rows are put in a random order fixed by seed, so the same split can be made again. With shuffle off the original order is kept and the earliest rows go to training.
- split_indices cuts that order into three runs of indices: train, validation and test.
- If stratify is on, each class is cut separately with the same fractions, so every part has the same class shares as the whole.
- split applies the indices to the arrays and returns the six pieces by name.
- kfold deals the rows into n_folds groups. Each group is the validation set once while the others train.
- group_split cuts the list of distinct group ids, not the rows, so all rows of one user or patient land in the same part.
Watch out for
- Any step fitted before the split, such as scaling, imputing or selecting columns, has seen the test rows. Split first, fit on the training part, then apply to the rest.
- If rows from the same person or the same source appear in both training and test data, the model is tested on near copies of what it saw. Use group_split.
- Shuffling time-ordered data lets the model train on the future and be tested on the past. Turn shuffle off so the test rows come last.
- Choosing settings by looking at the test score turns the test set into a second validation set. The reported number is then too optimistic.
- A small test set gives a noisy score. A difference of one or two points between models may be chance.
Use cases
When to use it
At the start of every modelling project, before any statistic is computed from the data. Use kfold when data is scarce, stratify when a class is rare, group_split when rows come in related clusters, and shuffle off for time-ordered data.
In industry
- Machine learning research
- Benchmarks such as ImageNet publish fixed training and validation sets and keep test labels private, so results are comparable.
- Healthcare
- Clinical models are split by patient, not by visit, so that records of one person never appear in both training and test data.
- Forecasting
- Demand and finance models are tested on the latest period with shuffling turned off, to mimic predicting the future.
Choosing it: what must hold
- Enough rows that each part is representative. With little data, use cross-validation folds.
- Rows that are independent, or a grouping column so that related rows stay in the same part.
- The split made before any step that learns from data, such as scaling, imputation or feature selection.
- A test set used once, at the end. Tuning against it makes its score too optimistic.
When to choose something else
| If | Use instead |
|---|---|
| The data are ordered in time | A chronological split with shuffle off, or rolling-origin evaluation |
| Several rows belong to the same user, patient or device | A group split |
| Classes are imbalanced | A stratified split, so every part keeps the class shares |
| The data set is small | K-fold cross-validation |
Math foundations
Sizes of the parts
Test and validation sizes are rounded and training takes the remainder, so the three parts always cover every row exactly once.
Uncertainty of a test accuracy
An accuracy measured on rows is an estimate. Its standard error shrinks only with the square root of the test size, so four times the rows halves the noise.
Cross-validation estimate
The model is trained times, each time leaving out one fold, and the validation errors are averaged. Every row is used for validation exactly once.
Stratification
Each part keeps the class shares of the full data, up to rounding. Without it a rare class can by chance be nearly absent from a small part.
Symbols
- the total number of rows
- test_fraction and val_fraction
- the number of rows in each part
- the accuracy measured on the test part
- standard error, the typical size of the chance error in an estimate
- n_folds
- the validation error when fold f is held out
- the number of rows of class c
Worked by hand
Split rows with fractions 0.7, 0.15 and 0.15. A model then scores an accuracy of 0.90 on the test part. How precise is that number?
The parts hold 700, 150 and 150 rows. The measured 0.90 is uncertain by about 2.4 points, so a rival model at 0.92 on the same test set is not clearly better.
Visual example
Loading the example.
Try this
- Turn shuffle off: the test part becomes the last rows, where class 1 is common, and its class share no longer matches the table.
- Turn shuffle back on and step through the seeds: the class 1 share of the small parts jumps around. Then turn stratify on.
- Shrink test_fraction to 0.05 and read how wide the uncertainty of a measured accuracy becomes.
Code sample
import numpy as np
from impl import Splitter
from config import SplitterConfig
X = np.arange(40).reshape(20, 2)
y = np.array([0] * 15 + [1] * 5)
splitter = Splitter(SplitterConfig(train_fraction=0.6, val_fraction=0.2, test_fraction=0.2, stratify=True))
parts = splitter.split(X, y) # X_train, y_train, X_val, y_val, X_test, y_test
folds = splitter.kfold(len(X), y) # list of (train_idx, val_idx)Read the implementation (111 lines)
"""Train / validation / test splitting, k-fold cross-validation and group-aware splitting.
NumPy only. Every method returns integer row indices, so the same split can be applied to features, labels
and any other array that shares the row order. Splits are reproducible from the seed in the config.
"""
from __future__ import annotations
import numpy as np
try:
from .config import SplitterConfig
except ImportError: # run from the template's own folder
from config import SplitterConfig
class Splitter:
"""Splits row indices into train, validation and test parts."""
def __init__(self, config: SplitterConfig | None = None) -> None:
self.config = config or SplitterConfig()
def _order(self, n: int) -> np.ndarray:
"""Row order to cut: a seeded permutation when shuffling, else 0..n-1."""
if self.config.shuffle:
return np.random.default_rng(self.config.seed).permutation(n)
return np.arange(n)
def _cut(self, order: np.ndarray) -> tuple[np.ndarray, np.ndarray, np.ndarray]:
"""Cut an index order into (train, val, test) by the configured fractions."""
n = len(order)
n_test = int(round(n * self.config.test_fraction))
n_val = int(round(n * self.config.val_fraction))
n_train = n - n_val - n_test
return order[:n_train], order[n_train:n_train + n_val], order[n_train + n_val:]
def split_indices(self, n: int, y=None) -> tuple[np.ndarray, np.ndarray, np.ndarray]:
"""Return (train, val, test) index arrays that together cover 0..n-1 exactly once.
n: number of rows. y: labels, shape (n,), required when `stratify` is on; each class is then cut
separately so its share is the same in every part.
"""
if n <= 0:
raise ValueError("n must be positive")
if not self.config.stratify:
return self._cut(self._order(n))
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}")
order = self._order(n)
parts: tuple[list, list, list] = ([], [], [])
for cls in np.unique(y):
members = order[y[order] == cls] # this class, in shuffled order
for part, idx in zip(parts, self._cut(members)):
part.append(idx)
out = []
for part in parts:
idx = np.concatenate(part) if part else np.array([], dtype=int)
out.append(np.sort(idx) if not self.config.shuffle else idx[np.argsort(np.argsort(order)[idx])])
return out[0], out[1], out[2]
def split(self, X, y=None) -> dict:
"""Split arrays. X: shape (n, ...). y: optional, shape (n, ...).
Returns a dict with keys X_train, X_val, X_test (and y_train, y_val, y_test when y is given).
"""
X = np.asarray(X)
y_arr = None if y is None else np.asarray(y)
parts = self.split_indices(X.shape[0], y_arr)
out = {}
for name, idx in zip(("train", "val", "test"), parts):
out[f"X_{name}"] = X[idx]
if y_arr is not None:
out[f"y_{name}"] = y_arr[idx]
return out
def kfold(self, n: int, y=None) -> list[tuple[np.ndarray, np.ndarray]]:
"""Return `n_folds` pairs (train_idx, val_idx). Every row is in exactly one validation fold.
With `stratify` on, the rows of each class are dealt round-robin to the folds, so every fold has
close to the full data's class proportions.
"""
k = self.config.n_folds
if n < k:
raise ValueError(f"cannot make {k} folds from {n} rows")
order = self._order(n)
if self.config.stratify:
if y is None:
raise ValueError("stratify needs the labels y")
y = np.asarray(y)
order = order[np.argsort(y[order], kind="stable")] # group by class, shuffled inside each class
fold_of = np.empty(n, dtype=int)
fold_of[order] = np.arange(n) % k
else:
fold_of = np.empty(n, dtype=int)
for f, chunk in enumerate(np.array_split(order, k)):
fold_of[chunk] = f
everything = np.arange(n)
return [(everything[fold_of != f], everything[fold_of == f]) for f in range(k)]
def group_split(self, groups) -> tuple[np.ndarray, np.ndarray, np.ndarray]:
"""Split so that all rows of one group (one user, one patient, ...) land in the same part.
groups: group id per row, shape (n,). The fractions apply to the number of groups, not rows.
"""
groups = np.asarray(groups)
unique, inverse = np.unique(groups, return_inverse=True)
parts = self._cut(self._order(len(unique)))
rows = np.arange(len(groups))
return tuple(rows[np.isin(inverse, part)] for part in parts) # type: ignore[return-value]- Repository
- Not published yet
- Needs
- Python 3.10 and NumPy
- Tests
- 9, run with
python3 -m unittest -v
Practice
Make 1000 rows with a label where one class is 5 percent of the data. Call Splitter.split_indices with the default SplitterConfig and count the rare class in each part. Repeat with stratify on and compare. Call kfold and confirm that every row is in exactly one validation fold. Then give each row one of 100 user ids and check with group_split that no id appears in two parts.
Check on learning
- Why are three parts needed and not two? What goes wrong if the same held-out rows are used both to choose settings and to report the final score?
A way to think about it
Trying many settings and keeping the best on a fixed set of rows is itself a way of fitting to those rows. Think about the best of twenty noisy scores.
- A medical dataset has several scans per patient. A random row split gives 97 percent accuracy and a patient-level split gives 82 percent. Which number describes the model's use on a new patient, and why do they differ?
A way to think about it
Ask what the model could learn about a patient from their other scans, and whether a new patient offers that shortcut.
- You have 200 labelled rows. Compare a single 80/20 split with 5-fold cross-validation in terms of how reliable the performance estimate is and how much it costs.
A way to think about it
Count how many rows contribute to the score in each scheme, using the standard error formula. Then count how many times the model is trained.
- For stock prices, why does a shuffled split overstate performance even when no row is duplicated?
A way to think about it
Neighbouring days are strongly related. With a shuffle, the days just before and after a test day are in training.