Training, Validation and Test Sets and the Job of Each
Understand what each data split is for, how to create splits that mirror real use and how a test set quietly loses its value.
Key takeaways
- Parameters are fitted on training data, choices are made on validation data and the final claim rests on test data.
- Picking the best of many candidates makes the winning validation score optimistic, even if no model is truly better.
- Split in a way that mirrors deployment: by time, by person or by site when those matter.
- Fit scalers, imputers, selectors and resampling on training data only, then apply them elsewhere.
- Every decision informed by the test set turns it into another validation set.
The training set is what the model learns from. The validation set is what you use to choose between models and settings. The test set is held back to estimate how the final choice performs on data that influenced nothing. In short: train fits, validation tunes, test reports.
The reason for three sets is that any data used to make a decision starts to look better than the future will. Each split protects one kind of judgment from that effect.
The three jobs
| Split | Used for | How often you look | What leaks if misused |
|---|---|---|---|
| Training | Fitting parameters and preprocessing | Constantly | Memorized examples look like skill |
| Validation | Comparing models, features, thresholds | Often | The choice fits this sample's quirks |
| Test | Estimating final performance | Once, at the end | The reported number becomes optimistic |
Think of practice problems, a mock exam and the real exam. If you keep retaking the real exam until you like the score, it no longer measures what you know.
Naming varies. Some papers and tools call the validation set a development set, and a few swap the words validation and test. Say what each split was used for, and nobody will be confused.
Why the winner looks too good
Suppose 20 candidate models are all truly 80 percent accurate and you score each on 500 validation examples. A single score has a standard error of √(0.8 × 0.2 / 500) ≈ 0.018. This simulation treats the scores as independent.
import numpy as np
rng = np.random.default_rng(0)
true_acc, n_val, n_models = 0.80, 500, 20
best_val, fresh = [], []
for trial in range(2000):
val = rng.binomial(n_val, true_acc, size=n_models) / n_val
best_val.append(val.max())
fresh.append(rng.binomial(n_val, true_acc) / n_val)
print(round(np.mean(best_val), 3), round(np.mean(fresh), 3)) On average, the best validation score comes out near 0.833, while the same model on fresh data scores about 0.80. More than three points of apparent skill came from selection alone. Real candidates are correlated, since they share data and errors, which usually shrinks the effect, but it does not vanish. Repeated tuning explores this further.
How big should each be?
Common starting points are 60/20/20 or 80/10/10 percent. These are habits, not laws. What matters is the number of examples in validation and test, and especially the number of rare cases.
With millions of rows, 1 percent can be plenty for testing. With 500 rows, a 100-row test set gives an accuracy near 90 percent an uncertainty of roughly ±6 points at 95 percent confidence. In that situation, use cross-validation for choosing, and be candid about the uncertainty of any final estimate.
Work backward from the smallest difference you need to detect. If a one-point change matters, a few hundred test examples will not show it.
When you can do without one of them
Not every project needs all three as fixed slices. If you compare nothing and tune nothing, fitting one prespecified model, a training set and a test set suffice. In practice this is rare, because looking at a result and changing something is itself tuning.
Cross-validation replaces a fixed validation set by rotating the role. The development data is cut into folds, and each fold takes a turn as validation while the rest trains. Every row eventually contributes to both jobs, though never at the same time. A separate test set still sits outside the rotation.
Cross-validation costs more compute, since each candidate is trained several times. For large neural networks that is often unaffordable, and a single large validation set is the norm. For a few thousand rows of tabular data, rotation is cheap and much steadier than one small slice.
Some models offer a built-in estimate. A random forest can score each row using only the trees that did not see it. That is useful during development, but it does not replace a test set after you have used it to make choices, and it ignores grouping or time order unless the sampling respects them.
Making the splits
In scikit-learn, two calls produce a 60/20/20 split.
from sklearn.datasets import make_classification
from sklearn.model_selection import train_test_split
X, y = make_classification(n_samples=1000, random_state=0)
X_rest, X_test, y_rest, y_test = train_test_split(
X, y, test_size=0.2, stratify=y, random_state=0)
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(X_train.shape, X_val.shape, X_test.shape)
# (600, 20) (200, 20) (200, 20) The second fraction is 0.25 because a quarter of the remaining 80 percent is 20 percent of the whole. Stratifying keeps class proportions similar across splits.
Split the way you will use the model
A random split assumes that rows are interchangeable. Often they are not.
- Groups. If one patient, user or device contributes many rows, keep each one entirely in one split. Otherwise the model can recognize the individual. See group-aware splits.
- Time. If you will predict the future, train on earlier periods, validate on later ones and test on the latest. Leave a gap if labels take time to settle.
- Sites. If the model must work in new locations, hold out whole locations.
- Duplicates. Remove or group near-identical records before splitting.
Ask what will be new when the model is used, and make that same thing new in the test set.
Rare classes and small slices
With rare outcomes, a random split can leave a validation set holding very few positives, or occasionally none. Stratify on the label so each split receives its share, and count the positives in each before you start.
Stratifying and grouping can conflict. If all positives come from a handful of customers, keeping customers whole makes the class proportions lumpy. Prefer the grouping, since it protects against a real leak, and use grouped folds that balance classes as well as they can.
Do the same count for the subpopulations you care about. A test set of 5,000 rows sounds generous until you find that one region contributes 30. You might deliberately collect extra test examples for small but important groups. If you do, report each group separately and reweight to the real mix when stating an overall figure, so the enlarged groups do not distort it.
Hypothetical leak, step by step
Say you build a model to recognize a manufacturing defect from photographs, and each physical part was photographed five times. A random split by image scatters those five shots across training and test. The model can then match a test photo to a near twin it has already seen, using a scratch on the fixture or the angle of a shadow.
The test score looks superb. On new parts it drops sharply. Splitting by part, or better by production batch, would have shown the truth early. Nothing in the code raised an error, which is why the split rule deserves a second pair of eyes.
Preprocessing belongs to training
Means used for scaling, values used to fill gaps, the list of selected features and any synthetic oversampled rows must all be derived from training data. Computing them on the full dataset first lets information from validation and test slip into the model.
Resample only the training portion. Validation and test sets should keep the class proportions you expect in use, or your metrics will describe a world that does not exist. Pipelines make this discipline automatic, as in fitting preprocessing on training data.
After the choices are made
Once settings are fixed, many teams refit on training and validation data combined, then evaluate on test. This usually helps because more data is used, though the final model is then slightly different from the one you validated. With early stopping, decide in advance how to set the number of rounds for the refit.
Then score the test set and report the result, with an interval and a baseline. If the number disappoints, say so. You may continue working, but a further test number on the same data is no longer a clean estimate.
Keeping a test set useful
A test set wears out as it informs decisions, including small ones: dropping a feature because test errors suggested it, or rerunning until a seed looks good. Over a long project or a shared benchmark, this adds up.
Some protections: restrict access, log every evaluation, refresh the test set with newly collected data from time to time, and keep a second untouched set for major milestones. Also check that it still resembles current traffic. An old test set can be perfectly clean and no longer relevant. Long-lived test sets covers maintenance.
Quick diagnosis when splits disagree
| Pattern | Likely explanation |
|---|---|
| Training far better than validation | Overfitting, or leakage within training |
| Validation far better than test | Heavy tuning, or the periods differ |
| All three excellent, production poor | Leakage shared by all splits, or a shifted world |
| Validation better than training | Easier validation rows, or training-only noise such as dropout |
None of these proves a cause. Each tells you where to look next, usually by comparing feature distributions and reading individual rows from the split that behaves oddly.
A habit worth adopting
Write the split rule down before modeling, and save the row identifiers that belong to each split. When new data arrives, assign it by a stable rule, such as a hash of the customer identifier, so that nobody migrates from test to training between runs. A saved split also lets a colleague reproduce your numbers exactly and argue with your conclusions on equal terms.