Sub topic 11
Leave-one-out and leave-p-out
This chapter assumes you know k-fold cross-validation, the scikit-learn fit/predict API, and the bias and variance trade-off from the chapter on choosing k. Leave-one-out and leave-p-out are the extreme end of the k scale. They are useful in a few situations and costly or misleading in many others.
Leave-one-out (LOO)
Leave-one-out cross-validation is k-fold with k equal to the number of samples, n. Each sample is the test set exactly once. The model trains on the other n − 1 samples. You get n scores, one per sample, and you average them.
import numpy as np
from sklearn.model_selection import LeaveOneOut
X = np.arange(10).reshape(5, 2)
for train_idx, test_idx in LeaveOneOut().split(X):
print("train:", train_idx, "test:", test_idx)Each training set has 4 samples and each test set has 1 sample. No random seed is needed because the splits are deterministic.
LOO has two main strengths:
- Low bias. Each model trains on almost all the data, so it resembles the final model trained on everything. This matters on very small datasets, where losing 20% of the data to a test fold changes the model noticeably.
- No randomness. Two runs give the same result.
Its costs
LOO fits n models. With 50 samples that is cheap. With 50,000 samples it is usually impractical.
The estimate can also have high variance. The n training sets overlap almost completely, so the n fitted models are highly correlated and their errors are correlated too. Averaging correlated values reduces noise less than averaging independent ones. In practice, 5-fold or 10-fold often gives an estimate that is just as good or better.
A single LOO test set holds one sample, so you cannot compute a per-fold metric such as accuracy, F1, or R². Each fold's accuracy is either 0 or 1, and R² is undefined for one point. Instead, collect the n predictions and compute the metric once on all of them.
from sklearn.datasets import load_iris
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import LeaveOneOut, cross_val_predict
from sklearn.metrics import accuracy_score
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
X, y = load_iris(return_X_y=True)
model = make_pipeline(StandardScaler(), LogisticRegression(max_iter=1000))
pred = cross_val_predict(model, X, y, cv=LeaveOneOut())
print(f"LOO accuracy: {accuracy_score(y, pred):.3f}")Note that the scaler is inside the pipeline, so it is refit on each set of 149 training samples. This keeps the leakage rules from earlier chapters in force.
Leave-p-out (LPO)
Leave-p-out tests on every possible subset of p samples. LOO is the special case p = 1. The number of splits is the binomial coefficient C(n, p), which grows very fast.
from math import comb
from sklearn.model_selection import LeavePOut
import numpy as np
X = np.arange(8).reshape(4, 2)
lpo = LeavePOut(p=2)
print("splits:", lpo.get_n_splits(X))
for train_idx, test_idx in lpo.split(X):
print("train:", train_idx, "test:", test_idx)
print("n=100, p=2:", comb(100, 2))
print("n=100, p=5:", comb(100, 5))For 4 samples and p = 2 there are 6 splits. For 100 samples, p = 2 gives 4,950 splits and p = 5 gives 75,287,520. Test sets also overlap heavily, which adds to the correlation problem. LPO is mainly a theoretical tool or a choice for tiny datasets. For larger data, use ShuffleSplit or repeated k-fold to sample random splits instead of enumerating all of them.
Choosing between them
| Method | Number of fits | Bias | Typical use |
|---|---|---|---|
| 5- or 10-fold | 5 or 10 | Slightly higher | Default choice |
| Leave-one-out | n | Lowest | Very small datasets, cheap models |
| Leave-p-out | C(n, p) | Low | Tiny datasets, theory |
Exercise
You have 40 samples, a fast model, and a classification task. You run LOO and want an F1 score. Why can't you average per-fold F1 scores, and what do you do instead?
Show answer
Each LOO test fold has one sample, so a per-fold F1 is 0, 1, or undefined and the average is meaningless. Use crossvalpredict with LeaveOneOut to collect all 40 out-of-fold predictions, then compute F1 once on the full prediction vector and the true labels.
Exercise
How many fits does leave-p-out with p = 3 require on 30 samples?
Show answer
C(30, 3) = 4,060 fits.