Sub topic 11
Leave-one-out and leave-p-out
This chapter assumes you know how k-fold cross-validation works and how to run cross_val_score in scikit-learn. It also assumes you know the bias and variance trade-off for choosing k. Leave-one-out and leave-p-out are the extreme end of that trade-off: the number of folds grows until each test set is tiny.
The idea
In k-fold cross-validation you split the data into k folds. Each fold takes one turn as the test set while the model trains on the rest. Leave-one-out cross-validation (LOO or LOOCV) sets k equal to the number of samples n. Each test set holds exactly one sample, and each training set holds the other n - 1 samples.
Leave-p-out (LPO) generalizes this. It tests on every possible subset of p samples and trains on the remaining n - p. LOO is the special case p = 1.
Two properties set these methods apart from k-fold:
- They are exhaustive. They use every possible test subset of the given size, so nothing is random. There is no shuffling and no seed, and every run gives the same result.
- Each fold has very little test data. A single fold score is close to meaningless alone, and only the aggregate is useful.
Leave-one-out in scikit-learn
LeaveOneOut yields n splits. The example below uses five samples so the splits fit on screen.
import numpy as np
from sklearn.model_selection import LeaveOneOut
X = np.arange(10).reshape(5, 2)
loo = LeaveOneOut()
print("number of splits:", loo.get_n_splits(X))
for train_idx, test_idx in loo.split(X):
print("train:", train_idx, "test:", test_idx)It prints five splits. The first trains on indices 1 to 4 and tests on index 0, the second tests on index 1, and so on. Every sample is tested exactly once.
Using LOO with cross_val_score
You can pass LeaveOneOut() as the cv argument. Keep the preprocessing inside a pipeline, exactly as in k-fold, so the scaler is refit on each training set of n - 1 samples.
from sklearn.datasets import load_breast_cancer
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import LeaveOneOut, cross_val_score
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
X, y = load_breast_cancer(return_X_y=True)
model = make_pipeline(StandardScaler(), LogisticRegression(max_iter=1000))
scores = cross_val_score(model, X, y, cv=LeaveOneOut(), scoring="accuracy")
print(len(scores), set(scores.tolist()))
print(f"LOO accuracy: {scores.mean():.3f}")This fits 569 models. Each fold score is either 0.0 or 1.0, because a single sample is either classified correctly or not. The mean of those values is the accuracy.
Metrics that break with one test sample
Many metrics are undefined on a single sample, which causes errors and silent mistakes:
- R² compares errors to the variance of the test targets. With one target the variance is zero, so scikit-learn returns
nanand warns. - ROC AUC needs both classes in the test set. A one-sample fold cannot supply that, so
cross_val_scorewithscoring="roc_auc"fails or returnsnan. - Averaging per-fold F1 or precision gives distorted numbers, because most folds have no positives or no predictions to score.
The fix is to pool the predictions and compute the metric once. cross_val_predict returns one out-of-fold prediction per sample. Use method="predict_proba" or method="decision_function" if the metric needs scores.
from sklearn.datasets import load_breast_cancer
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import roc_auc_score
from sklearn.model_selection import LeaveOneOut, cross_val_predict
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
X, y = load_breast_cancer(return_X_y=True)
model = make_pipeline(StandardScaler(), LogisticRegression(max_iter=1000))
proba = cross_val_predict(model, X, y, cv=LeaveOneOut(), method="predict_proba")
print(f"pooled LOO AUC: {roc_auc_score(y, proba[:, 1]):.3f}")Why use LOO: bias
A model trained on n - 1 samples is almost the same model as one trained on all n. So the LOO estimate has very low bias as an estimate of performance when the model is trained on your full dataset. With 5-fold cross-validation the models train on 80% of the data. If your learning curve is still rising at that size, 5-fold is pessimistic. LOO avoids that problem, which matters most when n is small and every sample counts.
Why avoid LOO: variance and cost
Variance. The n training sets differ by only two samples, so the n fitted models are nearly identical. Their errors are highly correlated, and averaging correlated quantities reduces variance less than averaging independent ones. LOO estimates are therefore often described as having higher variance than 5-fold or 10-fold. This is a tendency, not a law. The size of the effect depends on the model's stability, and for very stable models LOO is fine. Because no unbiased estimator of the variance of cross-validation exists, you cannot easily measure it from a single run.
Cost. LOO fits the model n times. For 100 samples and a fast model that is trivial. For 100,000 samples, or for a neural network, it is impractical. Ten-fold needs only 10 fits.
Instability with majority-vote behavior. Consider a perfectly balanced dataset with 10 samples of each class. Hold out one sample of class A and the training set has 9 A and 10 B. A model that predicts the training majority class then predicts B, which is wrong. Every fold fails and the estimated accuracy is 0%, even though a majority-class predictor should score about 50%. This is a known artifact. Unstable, high-variance models such as 1-nearest-neighbor with ties, or models that effectively memorize class frequencies, can show it. Be suspicious of a LOO score that is far below chance on balanced data.
No stratification. A one-sample test set cannot preserve class proportions, so there is nothing to stratify.
A shortcut for linear models
For some models, LOO needs no refitting at all. For ordinary least squares, the LOO residual for sample i equals the ordinary residual divided by (1 - hii). Here hii is the diagonal of the hat matrix H = X(XᵀX)⁻¹Xᵀ. The mean of the squared LOO residuals is known as the PRESS statistic divided by n. Ridge regression has an analogous formula, and scikit-learn's RidgeCV uses it by default to pick the penalty efficiently.
The code below checks the shortcut against brute-force LOO.
import numpy as np
from sklearn.linear_model import LinearRegression
from sklearn.model_selection import LeaveOneOut, cross_val_predict
rng = np.random.default_rng(0)
X = rng.normal(size=(30, 3))
y = X @ np.array([1.0, -2.0, 0.5]) + rng.normal(scale=0.5, size=30)
pred = cross_val_predict(LinearRegression(), X, y, cv=LeaveOneOut())
brute_mse = np.mean((y - pred) ** 2)
Xd = np.column_stack([np.ones(len(X)), X])
H = Xd @ np.linalg.inv(Xd.T @ Xd) @ Xd.T
resid = y - H @ y
shortcut_mse = np.mean((resid / (1 - np.diag(H))) ** 2)
print(round(brute_mse, 6), round(shortcut_mse, 6))Both numbers match. This is the main case where LOO is both exact and cheap. If your model has such a closed form, prefer it over looping.
Leave-p-out
LeavePOut(p) produces one split for every combination of p test samples. The count is the binomial coefficient C(n, p), which grows very fast.
import numpy as np
from sklearn.model_selection import LeavePOut
X = np.arange(10).reshape(5, 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)With n = 5 and p = 2 there are C(5, 2) = 10 splits. The table shows how the count grows for n = 100.
| p | Number of splits C(100, p) |
|---|---|
| 1 | 100 |
| 2 | 4,950 |
| 3 | 161,700 |
| 5 | 75,287,520 |
Test sets overlap heavily across splits, so the estimates are strongly correlated. Leave-p-out is rarely worth its cost beyond p = 2. If you want many random train/test splits with a larger test fraction, ShuffleSplit or RepeatedKFold is a cheaper choice, since they sample from the possible splits instead of enumerating them.
Grouped variants
When samples are not independent, leaving out one sample leaks information from its group mates into training. The grouped versions leave out whole groups:
LeaveOneGroupOutholds out every sample of one group per split.LeavePGroupsOut(n_groups=p)holds out p groups per split.
Both need a groups array passed to split or cross_val_score. Leave-one-subject-out is a standard evaluation for medical and sensor data.
Choosing a method
Common mistakes
- Computing R² or AUC per fold with LOO, then averaging. Pool predictions with
cross_val_predictinstead. - Reading a low LOO accuracy on balanced data as proof of a bad model, without considering the majority-class artifact.
- Using LOO to tune hyperparameters and then reporting the same LOO score as final performance. The selection step biases it upward. Use nested cross-validation, as covered in a later chapter.
- Choosing
LeavePOutwith a large n and p, then waiting for a run that would take days. Checkget_n_splitsfirst. - Using plain LOO on grouped or time-ordered data. Use the grouped or forward-chaining methods instead.
Exercise
You have a dataset with 40 samples and a ridge regression model. A colleague proposes LeavePOut(p=3) because "more held-out data per fold is more reliable." How many splits would that create, and what would you suggest instead?
Show answer
C(40, 3) = 40 x 39 x 38 / 6 = 9,880 splits, versus 40 for LeaveOneOut. The test sets overlap heavily, so the extra splits add cost without much independent information. Suggest LeaveOneOut, which for ridge regression has a closed-form shortcut (and is what RidgeCV uses by default), or repeated k-fold if a larger test fraction is wanted.
Exercise
A balanced binary dataset (30 samples of each class) is evaluated with LeaveOneOut using a model that always predicts the majority class of its training set. What accuracy does LOO report, and why?
Show answer
0%. When one sample of class A is held out, the training set has 29 A and 30 B, so the model predicts B and is wrong. The same happens for a held-out B sample. Every fold fails, even though the same model scores about 50% on fresh balanced data. This shows that LOO can be strongly misleading for models that depend on training class frequencies.