Sub topic 2
The Holdout Split and Why One Split Is Not Enough
This chapter assumes you have trained a scikit-learn model with fit and predict. It also assumes you know what overfitting is and can read accuracy as a metric. The previous chapter explained that training-set performance is optimistic. This chapter covers the simplest fix, the holdout split, and shows where it breaks down.
The idea behind a holdout split
A holdout split divides your labelled data into two parts before training:
- The training set is the data the model learns from.
- The test set (also called the holdout set) is data the model never sees during training. You use it once, to measure performance.
Because the model did not learn from the test set, the score on it estimates how the model behaves on new data. Memorizing the training set cannot raise that score.
A minimal holdout example
train_test_split does the work. The pipeline here scales the features and fits a logistic regression. Putting the scaler in a pipeline means it learns its statistics from the training data only. A later chapter covers why that matters.
from sklearn.datasets import load_breast_cancer
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import train_test_split
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
X, y = load_breast_cancer(return_X_y=True)
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.2, stratify=y, random_state=0
)
model = make_pipeline(StandardScaler(), LogisticRegression(max_iter=1000))
model.fit(X_train, y_train)
print("train accuracy:", model.score(X_train, y_train))
print("test accuracy: ", model.score(X_test, y_test))Each argument has a job:
| Argument | Effect |
|---|---|
| `test_size=0.2` | Puts 20% of the samples in the test set. |
| `stratify=y` | Keeps the class proportions the same in both sets. |
| `random_state=0` | Fixes the shuffle so the split can be reproduced. |
| `shuffle=True` (default) | Shuffles rows before splitting, so row order does not decide which set a sample lands in. |
The training accuracy will usually be at least as high as the test accuracy. The test number is the one to trust. It is still only one number, and the rest of the chapter is about how far to trust it.
How big should the test set be?
A common starting point is 20% to 30% of the data for testing. The choice is a trade-off:
- A larger test set gives a more stable score, because it averages over more samples.
- A smaller training set gives a weaker model, because the model sees less data. The score then understates what a model trained on all the data would achieve.
With a small dataset you cannot fix both problems at once. Taking data from the training set to steady the test score makes the model worse. Taking data from the test set to improve the model makes the score noisier. This tension is the main motivation for cross-validation.
Why one split is noisy
The test score is a statistic computed from a random sample, and a different random split gives a different sample. Two sources of randomness are at work:
- Which samples land in the test set. If the test set happens to contain several hard cases, the score drops. If it contains mostly easy ones, the score rises.
- Which samples land in the training set. The fitted model itself changes slightly with its training data. This matters most for high-variance models such as deep decision trees, and for small datasets.
You can estimate the size of the first effect with a formula. If the true accuracy is p and the test set has n independent samples, the standard error of the measured accuracy is roughly sqrt(p * (1 - p) / n). For p = 0.95 and n = 114 (20% of this dataset), that is about 0.02, or two percentage points. Each test sample is worth almost one percentage point, so a few lucky or unlucky samples change the score visibly.
Seeing the noise directly
The next script repeats the same experiment with 100 different random seeds. Nothing changes between runs except which samples are held out.
import numpy as np
from sklearn.datasets import load_breast_cancer
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import train_test_split
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 = []
for seed in range(100):
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.2, stratify=y, random_state=seed
)
model.fit(X_train, y_train)
scores.append(model.score(X_test, y_test))
scores = np.array(scores)
print(f"min={scores.min():.3f} max={scores.max():.3f}")
print(f"mean={scores.mean():.3f} std={scores.std():.3f}")Run it and compare the minimum and maximum. They typically differ by several percentage points, even though the data, the model, and the split ratio never changed. If you had reported only the seed you happened to try first, your headline number could land anywhere in that range.
Three-way splits: train, validation, test
Most real projects choose among several models or settings, such as the regularization strength or the tree depth. If you pick the best option by its test score, you have used the test set to make a decision. The test score is then optimistic, because the winner was chosen partly for being lucky on that particular test set.
The standard remedy is a third set:
- The training set fits the model parameters.
- The validation set compares candidate models and settings.
- The test set is touched once, at the end, to report the final score.
from sklearn.datasets import load_breast_cancer
from sklearn.model_selection import train_test_split
X, y = load_breast_cancer(return_X_y=True)
# First carve off the final test set.
X_rest, X_test, y_rest, y_test = train_test_split(
X, y, test_size=0.2, stratify=y, random_state=0
)
# Then split the remainder into train and validation.
X_train, X_val, y_train, y_val = train_test_split(
X_rest, y_rest, test_size=0.25, stratify=y_rest, random_state=0
)
print(len(X_train), len(X_val), len(X_test))The second split takes 25% of the remaining 80%, which is 20% of the original data. The result is roughly a 60/20/20 split.
This costs data. Only about 60% of the samples are left for training, and the validation score has the same noise problem as the test score. On small datasets, both the model comparison and the final estimate become unreliable.
Failure modes of the holdout approach
| Problem | What happens | Typical cause |
|---|---|---|
| High-variance estimate | The score changes noticeably with the random seed. | Small test set, or a model that is sensitive to its training data. |
| Pessimistic estimate | The score is lower than a model trained on all data would achieve. | A large share of data held out of training. |
| Test-set reuse | The reported score is too optimistic. | Using the test score to choose models, settings, or features. |
| Unrepresentative split | Class proportions or data types differ between sets. | Rare classes with no stratification. |
| Unsuitable shuffling | The estimate does not match deployment conditions. | Related samples or time-ordered data split at random. |
The last two rows have their own chapters later: stratified, grouped, and time-ordered splitting. For now, note that a plain random split quietly assumes the samples are independent and the order does not matter. Real data often violates both assumptions.
From one split to many
The experiment above suggests the remedy. If a single split is a noisy draw, take several draws and look at all of them. Better still, arrange the draws so every sample is used for testing exactly once and for training in all the other rounds. Then no data is permanently set aside, and the final number is an average over several test sets instead of one.
That arrangement is k-fold cross-validation, covered in the next chapter. The holdout split is still useful. It is cheap, simple, and appropriate when you have a very large dataset, where the noise formula above gives a tiny standard error. It is also the right structure for the final untouched test set that many projects keep apart from any cross-validation.
Practical checklist
- Split before any preprocessing that learns from the data, such as scaling or imputation.
- Use
stratify=yfor classification so class proportions match across sets. - Set
random_stateso results can be reproduced, but do not shop for a favourable seed. - Look at the test set once, after all modelling decisions are final.
- If the score matters, repeat the evaluation with several splits and report the spread.
Exercise
You train a model, try 20 different hyperparameter settings, and pick the one with the highest accuracy on your 20% test set. You report that accuracy as the expected performance on new data. Name two reasons the number is unreliable, and say what change to the data split fixes the larger problem.
Show answer
First, the test set was used to choose among settings, so the winning score is partly selection luck and is optimistic. Second, even without selection, a single test set gives a noisy estimate, because a different random split would give a different score (about two percentage points of standard error for 114 samples at 95% accuracy). The fix for the larger problem is a three-way split: choose the setting on a separate validation set (or on cross-validation folds inside the training data), and score the chosen model once on a test set that played no part in the choice.
Exercise
A test set has 200 samples and the model's true accuracy is 0.90. Using the formula sqrt(p * (1 - p) / n), what is the approximate standard error of the measured accuracy, and what range covers about 95% of the scores you would expect across different random test sets (roughly two standard errors either side)?
Show answer
sqrt(0.90 * 0.10 / 200) = sqrt(0.00045), which is about 0.021. Two standard errors is about 0.042, so scores would typically fall between about 0.86 and 0.94. This ignores the extra variation from different training sets, so the real spread is somewhat larger.