Overview
The score that matters is the one on data the model has never seen, and you do not have that data yet. So you imitate it: hide some rows, fit on the rest, and score on the hidden ones. One such split gives one number, which depends on luck in which rows were hidden. Repeating the split in an organised way gives several numbers. Their average is a steadier estimate, and their spread shows how much to trust it.
A short history
Mervyn Stone in 1974 and Seymour Geisser in 1975 formalised cross-validation as a way to judge a model on data it was not fitted to. Bradley Efron introduced the bootstrap in 1979, and Leo Breiman's bagging work in the 1990s made scoring on the rows left out of each resample a standard tool. Ron Kohavi's 1995 comparison of cross-validation and the bootstrap helped establish stratified ten-fold cross-validation as a default.
How it works
- Pass
evaluatea factory, a function that builds a fresh, unfitted model withfitandpredict. splitsmakes the index pairs for the chosenmethod: one holdout split, folds, folds repeated with new shuffles, or bootstrap rounds.- For each pair a new model is fitted on the training rows and scored on the test rows with the chosen
metric. - The same model is also scored on its own training rows, so a large gap between the two reveals overfitting.
- The test scores are summarised in an
EvalResult: mean, standard deviation and a rough 95 percent interval. compareruns several factories on the same splits and names the one with the best mean.
Watch out for
- Any step that learns from data, such as scaling or feature selection, must happen inside the model the factory builds. Done before the split, it has seen the test rows and the estimate is too good.
- Fold scores share most of their training rows, so they are not independent and the 95 percent interval is usually somewhat too narrow.
- A bootstrap training set repeats rows and holds only about 63 percent distinct ones, so its out-of-bag score tends to be a little pessimistic.
- Shuffled k-fold on time-ordered data trains on the future. Use holdout with
shuffleoff, which tests on the last rows. - Comparing many models on the same splits and reporting the winner's score is optimistic, because the winner was chosen partly for its luck on those splits.
Use cases
When to use it
Whenever you need a number for how a model will do on new data. Use holdout when data is plentiful or ordered in time, k-fold when every row counts, repeated k-fold when the fold-to-fold noise is still too high, and the bootstrap for very small datasets.
In industry
- Clinical research
- Studies with a few hundred patients cannot spare a large test set, so prediction models are assessed with repeated k-fold cross-validation or the bootstrap.
- Marketing analytics
- A churn model built on millions of customers is judged on one large holdout set, which is cheap to compute and precise enough at that size.
- Model audits
- Comparing training and test scores fold by fold shows whether a model memorises its training rows, which reviewers ask about before approval.
Choosing it: what must hold
- A way to build a fresh, unfitted model for every split.
- All preprocessing fitted inside each training part, so nothing from the test rows leaks in.
- Rows that are independent, or a split method that respects their grouping or time order.
- Compute budget for one full training run per fold or bootstrap round.
When to choose something else
| If | Use instead |
|---|---|
| The scores will be used to pick hyperparameters or choose between models | The cross-validation strategies lesson, with a separate final test set |
| Rows of one entity are related, or the data is a time series | The group or time series strategy in the cross-validation strategies lesson |
| One training run takes days | A single holdout split from the data splitting lesson |
Math foundations
The cross-validation estimate
The average of the test scores over the splits. Each comes from a model that never saw the rows it is scored on.
Spread of the scores
The sample standard deviation of the split scores. It shows how much the result depends on which rows were held out.
A rough 95 percent interval
The mean plus and minus about two standard errors. It would be exact for independent, normally distributed scores. Folds overlap, so read it as a guide.
Rows left out by a bootstrap draw
Drawing rows with replacement misses any given row with this probability. So about 37 percent of rows are out of the bag and serve as the test set of that round.
The included ridge model
RidgeRegressionsolves least squares with an L2 penalty in closed form on centred data. It is there so the template runs alone, and gives ordinary least squares.
Symbols
- test score of split k
- number of splits
- mean of the split scores
- sample standard deviation of the split scores
- number of rows
- feature matrix with each column's mean subtracted
- targets and their mean
- strength of the ridge penalty
- fitted coefficient vector
Worked by hand
Five folds give the test MSE values 0.10, 0.12, 0.08, 0.11 and 0.09. Summarise them.
The estimate is an MSE of 0.10, with a rough interval from 0.086 to 0.114. A rival model at 0.105 would not be clearly worse.
Visual example
Loading the example.
Try this
- Press Next split and watch which rows train and which rows test each time.
- Raise the polynomial degree to 8: the training error keeps falling while the test error and its spread grow.
- Compare holdout with kfold at the same seed, then change the seed and see which estimate moves more.
Code sample
import numpy as np
from impl import Evaluator, RidgeRegression
from config import EvalValidationConfig
rng = np.random.default_rng(0)
X = rng.normal(size=(100, 3))
y = X @ np.array([1.0, -2.0, 0.5]) + 0.1 * rng.normal(size=100)
evaluator = Evaluator(EvalValidationConfig(method="kfold", n_splits=5, metric="mse"))
result = evaluator.evaluate(lambda: RidgeRegression(alpha=0.1), X, y)
print(result.summary()) # test MSE near the noise variance 0.01
best, results = evaluator.compare({"ols": RidgeRegression, "heavy": lambda: RidgeRegression(1000.0)}, X, y)
print(best) # olsRead the implementation (175 lines)
"""Model evaluation by resampling: holdout, k-fold, repeated k-fold and out-of-bag bootstrap.
NumPy only. `Evaluator.evaluate` takes a factory that builds a fresh model (anything with `fit(X, y)` and
`predict(X)`), fits it on each training part, scores it on the matching test part and returns the scores
with their mean, spread and a rough confidence interval. Two small reference models are included so the
template runs alone: closed-form ridge regression and a nearest-centroid classifier.
"""
from __future__ import annotations
from dataclasses import dataclass, field
from typing import Callable
import numpy as np
try:
from .config import EvalValidationConfig
except ImportError: # run from the template's own folder
from config import EvalValidationConfig
def _r2(y_true: np.ndarray, y_pred: np.ndarray) -> float:
total = float(((y_true - y_true.mean()) ** 2).sum())
return 1.0 - float(((y_true - y_pred) ** 2).sum()) / total if total > 0 else 0.0
# metric name -> (function(y_true, y_pred) -> float, higher_is_better)
SCORERS: dict[str, tuple[Callable, bool]] = {
"mse": (lambda t, p: float(((t - p) ** 2).mean()), False),
"mae": (lambda t, p: float(np.abs(t - p).mean()), False),
"r2": (_r2, True),
"accuracy": (lambda t, p: float((t == p).mean()), True),
}
class RidgeRegression:
"""Least squares with an L2 penalty, solved in closed form. alpha = 0 is ordinary least squares.
Minimises ||y - X w - b||^2 + alpha * ||w||^2. The intercept b is not penalised.
"""
def __init__(self, alpha: float = 0.0) -> None:
self.alpha = alpha
self.coef_: np.ndarray | None = None
self.intercept_: float = 0.0
def fit(self, X, y) -> "RidgeRegression":
"""X: shape (n, d). y: shape (n,)."""
X, y = np.asarray(X, dtype=float), np.asarray(y, dtype=float)
x_mean, y_mean = X.mean(axis=0), y.mean()
Xc = X - x_mean
gram = Xc.T @ Xc + self.alpha * np.eye(X.shape[1])
self.coef_ = np.linalg.lstsq(gram, Xc.T @ (y - y_mean), rcond=None)[0]
self.intercept_ = float(y_mean - x_mean @ self.coef_)
return self
def predict(self, X) -> np.ndarray:
"""X: shape (n, d). Returns shape (n,)."""
return np.asarray(X, dtype=float) @ self.coef_ + self.intercept_
class NearestCentroid:
"""Classifier that predicts the class whose training mean is closest (Euclidean distance)."""
def __init__(self) -> None:
self.classes_: np.ndarray | None = None
self.centroids_: np.ndarray | None = None
def fit(self, X, y) -> "NearestCentroid":
"""X: shape (n, d). y: class labels, shape (n,)."""
X, y = np.asarray(X, dtype=float), np.asarray(y)
self.classes_ = np.unique(y)
self.centroids_ = np.stack([X[y == label].mean(axis=0) for label in self.classes_])
return self
def predict(self, X) -> np.ndarray:
"""X: shape (n, d). Returns the predicted labels, shape (n,)."""
X = np.asarray(X, dtype=float)
distances = ((X[:, None, :] - self.centroids_[None, :, :]) ** 2).sum(axis=2)
return self.classes_[distances.argmin(axis=1)]
@dataclass
class EvalResult:
"""Outcome of one evaluation.
scores: test score of every split, in order.
train_scores: score of the same models on their own training rows (a large gap to `scores` means
overfitting).
mean, std: of `scores` (std with ddof=1, 0 for a single split).
ci95: mean +/- 1.96 * std / sqrt(n_splits). Folds share training rows, so the scores are not
independent and this interval is a rough guide, usually somewhat too narrow.
"""
method: str
metric: str
higher_is_better: bool
scores: list = field(default_factory=list)
train_scores: list = field(default_factory=list)
mean: float = 0.0
std: float = 0.0
ci95: tuple = (0.0, 0.0)
def summary(self) -> str:
"""One line for a log."""
return (f"{self.method} {self.metric}: {self.mean:.4f} +/- {self.std:.4f} over {len(self.scores)} "
f"split(s), train {float(np.mean(self.train_scores)):.4f}")
class Evaluator:
"""Estimate how well a model generalises, by fitting and scoring it on resampled splits."""
def __init__(self, config: EvalValidationConfig | None = None) -> None:
self.config = config or EvalValidationConfig()
def splits(self, n: int) -> list[tuple[np.ndarray, np.ndarray]]:
"""The (train_indices, test_indices) pairs the configured method uses for n rows."""
cfg = self.config
rng = np.random.default_rng(cfg.seed)
if cfg.method == "holdout":
order = rng.permutation(n) if cfg.shuffle else np.arange(n)
n_test = max(1, int(round(n * cfg.test_fraction)))
if n_test >= n:
raise ValueError(f"holdout needs at least 2 rows, got {n}")
# without shuffling the LAST rows are the test set, the right choice for time-ordered data
return [(np.sort(order[:-n_test]), np.sort(order[-n_test:]))]
if cfg.method == "bootstrap":
pairs = []
while len(pairs) < cfg.n_repeats:
drawn = rng.integers(0, n, size=n)
out_of_bag = np.setdiff1d(np.arange(n), drawn)
if out_of_bag.size: # for n >= 2 some row is almost always left out; redraw otherwise
pairs.append((drawn, out_of_bag))
return pairs
if n < cfg.n_splits:
raise ValueError(f"cannot make {cfg.n_splits} folds from {n} rows")
repeats = cfg.n_repeats if cfg.method == "repeated_kfold" else 1
pairs = []
for _ in range(repeats):
shuffled = cfg.shuffle or cfg.method == "repeated_kfold" # repeating without shuffling is pointless
order = rng.permutation(n) if shuffled else np.arange(n)
for fold in np.array_split(order, cfg.n_splits):
pairs.append((np.setdiff1d(order, fold), np.sort(fold)))
return pairs
def evaluate(self, model_factory: Callable, X, y) -> EvalResult:
"""Fit a fresh model on every training part and score it on the matching test part.
model_factory: function with no arguments that returns a new, unfitted model with
fit(X, y) and predict(X).
X: shape (n, d). y: shape (n,).
"""
cfg = self.config
X, y = np.asarray(X), np.asarray(y)
if X.shape[0] != y.shape[0]:
raise ValueError(f"X has {X.shape[0]} rows, y has {y.shape[0]}")
score, higher = SCORERS[cfg.metric]
result = EvalResult(method=cfg.method, metric=cfg.metric, higher_is_better=higher)
for train, test in self.splits(X.shape[0]):
model = model_factory()
model.fit(X[train], y[train])
result.scores.append(score(y[test], np.asarray(model.predict(X[test]))))
result.train_scores.append(score(y[train], np.asarray(model.predict(X[train]))))
count = len(result.scores)
result.mean = float(np.mean(result.scores))
result.std = float(np.std(result.scores, ddof=1)) if count > 1 else 0.0
half = 1.96 * result.std / np.sqrt(count)
result.ci95 = (result.mean - half, result.mean + half)
return result
def compare(self, factories: dict, X, y) -> tuple[str, dict]:
"""Evaluate several models on the SAME splits and return (name of the best, {name: EvalResult})."""
results = {name: self.evaluate(factory, X, y) for name, factory in factories.items()}
higher = SCORERS[self.config.metric][1]
best = (max if higher else min)(results, key=lambda name: results[name].mean)
return best, results- Repository
- Not published yet
- Needs
- Python 3.10 and NumPy
- Tests
- 8, run with
python3 -m unittest -v
Practice
Generate 100 rows of linear data with noise as in the template's README. Run Evaluator(EvalValidationConfig(method=m, metric="mse")).evaluate(lambda: RidgeRegression(alpha=0.1), X, y) for holdout, kfold, repeated_kfold and bootstrap. Print summary() and ci95 each time and compare the widths.
Check on learning
- You standardise the whole dataset and then run 5-fold cross-validation. The estimate comes out slightly better than production later shows. Trace the leak.
A way to think about it
Ask which rows contributed to the mean and standard deviation used to scale a training fold. Then decide where the scaler should be fitted.
- Holdout gives a single score of 0.91 and 5-fold gives 0.88 with a standard deviation of 0.04. Which would you report, and why might they differ?
A way to think about it
One number is a single draw. Check whether 0.91 is a surprising draw given a mean of 0.88 and that spread.
- The training score is 0.99 and the test score is 0.80 on every fold. What does the gap tell you, and name two changes that might close it.
A way to think about it
The model fits its training rows much better than new ones. Think about what makes a model less able to memorise: more data, a penalty, fewer features.
- Why is the 95 percent interval from k-fold usually too narrow?
A way to think about it
The formula assumes independent scores. Count how many training rows any two folds have in common.
- With 30 rows, why might the bootstrap or repeated k-fold serve you better than a single 80/20 holdout?
A way to think about it
A 20 percent holdout of 30 rows is 6 rows. Ask how much one mistaken prediction moves an accuracy computed on 6 rows.