Level 3 In-Depth AI · Classical Machine Learning
Training, Validation and Test Sets
Why you must hide some of your data from the model, how to split it into training, validation and test sets, and the many sneaky ways information leaks across the split and makes a bad model look good.
- Level
- ●●●●● Beginner
- Reading
- 12 min
- To learn it well
- 40 minutes to read, an hour to practise
- Builds on
- 4 concepts →
- Quiz
- 5 questions ↓
Read first
Supervised LearningThe full path from zero — 4 concepts before this one
- What Is AI?
- How Machines Learn
- Supervised, Unsupervised and Reinforcement Learning
- Supervised Learning
- Training, Validation and Test Sets
Read them roughly in this order. See it on the concept map →
Why it matters
A model is only useful if it works on data it has never seen: next month's transactions, tomorrow's patients, a sentence nobody has typed yet. But you can only measure performance on data you already have. The standard solution is simple: hide part of your data from the model, train on the rest, and then test on the hidden part as if it were the future.
This is the single most important habit in machine learning, and getting it wrong is the most common way projects fail. A model that scores 99% in the notebook and 60% in production has nearly always been tested on data that wasn't really hidden. Leaky evaluation has produced published medical-imaging results that didn't replicate, trading strategies that lost money on day one, and Kaggle competitors who led the public leaderboard and then tumbled down the private one. Every later chapter on evaluation (Overfitting and the Bias–Variance Tradeoff, Cross-Validation, Hyperparameter Tuning, Evaluation Metrics, Evaluating LLMs and Benchmarks) builds on the ideas here.
The intuition
A teacher who wants to know whether students understand algebra doesn't put the homework questions on the exam. A student could have memorised those answers without understanding anything. The exam uses new questions of the same kind.
Machine learning models are extraordinary memorisers. A big enough model can learn every training example by heart. So you need exam questions it has never seen. Split the data:
- The training set is the homework. The model sees these examples and their labels and fits its parameters to them.
- The test set is the final exam. It is locked away during development and used once, at the end, to estimate how the model will do in the real world. It is also called the holdout set.
There is a catch. During development you will make many decisions: which model, which features, how much Regularization: L1 and L2, when to stop training. If you make those decisions by checking the test score, the test set stops being a fair exam. You have tuned yourself to it, just as a student who sees the exam in advance and studies only those topics. So you need a third set:
- The validation set (also called the development set or dev set) is the mock exam. Use it as often as you like to compare options. Its score will end up slightly optimistic, because you chose whatever did best on it. That is exactly why the test set stays locked until the end.
Key idea Evaluate only on data that played no part in any decision. Train on the training set, choose using the validation set, and report the test set once. Anything that touched a decision is no longer a fair test.
How it works
Choosing the sizes
There is no magic ratio. You are trading off two needs: the model wants as much training data as possible, and your estimates need enough test examples to be precise.
- Small datasets (hundreds to a few thousand examples): a common choice is 60/20/20 or 70/15/15. With so little data, Cross-Validation is usually better than a single validation set, because it reuses every example for both training and validation.
- Large datasets (millions of examples): 98/1/1 is fine. One percent of ten million is 100,000 test examples, plenty for a precise estimate.
How precise is a test score? For accuracy, a rough guide is that the standard error is , where is the accuracy and the number of test examples. With 90% accuracy on 100 examples, that is , so the true accuracy could easily be anywhere from about 84% to 96%. On 10,000 examples the uncertainty shrinks to 0.003. Two models that differ by 1% on a 100-example test set are statistically indistinguishable.
Shuffle first
Data files are often sorted: by date, by class, by the hospital it came from. If you take the first 80% of rows for training, the test set may contain only patients from the last hospital, or only one class. Shuffle the rows randomly before splitting (unless time order matters, below). Fix the random seed so the split is reproducible.
Stratified splits
With rare classes, a random split can be unlucky. Here is a worked example. You have 20 examples, of which 4 are positive (20%). You randomly put 5 into the test set. What is the chance that the test set contains no positives at all?
The number of ways to choose 5 test examples from 20 is . The number of ways to choose them all from the 16 negatives is . (The notation , "n choose k", counts the ways to pick items from .) So:
More than a one-in-four chance that your test set can't measure the very thing you care about. A stratified split prevents this by splitting each class separately, so every set keeps the original class proportions: here, exactly 1 positive and 4 negatives in the test set. For classification, stratify by default. In scikit-learn it is one argument: stratify=y.
Group splits
Sometimes examples come in related clumps: several X-rays of the same patient, many sentences from the same document, many readings from the same machine. If one patient's scans land in both training and test, the model can recognise the patient (their anatomy, the scanner's quirks) rather than the disease, and the test score is inflated. A group split keeps every group entirely on one side. Ask: in real use, will the model see new patients, new documents, new customers? Then split by patient, document or customer. Scikit-learn provides GroupShuffleSplit and GroupKFold.
Time-based splits
When data has a time order and the model will predict the future, a random split cheats. Random test days are surrounded by training days, so the model effectively sees what happened the day before and the day after. In real use it will only ever have the past.
A time-based split trains on everything before a cut-off date and tests on everything after it. It is the only honest choice for forecasting (Time Series Forecasting), and a good idea for anything where the world drifts: fraud patterns, prices, user behaviour, the news. Often you also leave a gap between the training and test periods, to mimic the delay between training a model and deploying it.
Data leakage
Data leakage means information that wouldn't be available at prediction time sneaks into training or evaluation. It is the most dangerous bug in machine learning, because it makes models look better, and nobody goes looking for bugs in good results. The main forms:
- Target leakage: a feature that is a consequence of the label, or recorded after it. Predicting whether a patient has pneumonia using "was prescribed antibiotics"? The prescription comes after the diagnosis. The model will be superb in testing and useless at admission time. For every feature, ask: would I know this at the moment I need the prediction?
- Train–test contamination: any step fitted on the full dataset before splitting. Computing the mean and standard deviation for scaling, filling missing values with the average, choosing features by their correlation with the label, removing duplicates by comparison with the test set: if any of these use the test rows, the test rows have influenced the model. The fix is to split first and fit every preprocessing step on the training rows only. Scikit-learn's
Pipelinedoes this automatically. - Duplicates and near-duplicates: the same example, or nearly the same, in both sets. This is common with scraped web data, photos taken in bursts, and benchmark questions that also appear in a language model's training corpus (a big problem in Evaluating LLMs and Benchmarks).
- Leaking through the time order, as above.
The figure shows how big the effect can be, using real numbers from the code below.
Distribution shift
A random split assumes the future looks like the past: that training and test examples are drawn from the same population. In deployment that is often false. A model trained on one hospital's scanners meets another hospital's. A spam filter meets new kinds of spam. This is distribution shift, and no split of your existing data can fully measure it. The best defences are a test set collected the way production data will be (later in time, from new sources) and monitoring after launch (Monitoring and Data Drift).
In code
A split from scratch: shuffle the row numbers and cut. A decision tree with no limits memorises the training set perfectly, and the test set exposes it:
import numpy as np
from sklearn.datasets import load_breast_cancer
from sklearn.tree import DecisionTreeClassifier
X, y = load_breast_cancer(return_X_y=True)
rng = np.random.default_rng(0)
idx = rng.permutation(len(X)) # shuffle the row numbers
n_test = int(0.25 * len(X))
test, train = idx[:n_test], idx[n_test:] # 142 test rows, 427 training rows
tree = DecisionTreeClassifier(random_state=0).fit(X[train], y[train])
print("train accuracy:", tree.score(X[train], y[train]))
print("test accuracy: ", round(tree.score(X[test], y[test]), 3))
print("share benign: all", y.mean().round(3), " train", y[train].mean().round(3),
" test", y[test].mean().round(3))
# train accuracy: 1.0
# test accuracy: 0.866
# share benign: all 0.627 train 0.621 test 0.648
Training accuracy of 100% says nothing. Test accuracy of 86.6% is the real estimate. Notice also that random chance made the test set slightly more benign-heavy (64.8%) than the whole (62.7%). Passing stratify=y to scikit-learn's train_test_split would keep them equal.
Now leakage. The data is pure noise, so the honest accuracy is 50%:
import numpy as np
from sklearn.model_selection import train_test_split
from sklearn.feature_selection import SelectKBest, f_classif
from sklearn.linear_model import LogisticRegression
from sklearn.pipeline import make_pipeline
# Pure noise: 100 examples, 5,000 random features, random labels.
rng = np.random.default_rng(0)
X = rng.normal(size=(100, 5000))
y = rng.integers(0, 2, size=100) # nothing to learn: 50% is the truth
# WRONG: pick the 20 features most related to y using ALL the data, then split
X_sel = SelectKBest(f_classif, k=20).fit_transform(X, y)
X_tr, X_te, y_tr, y_te = train_test_split(X_sel, y, test_size=0.3, random_state=0, stratify=y)
leaky = LogisticRegression().fit(X_tr, y_tr)
print("leaky test accuracy: ", round(leaky.score(X_te, y_te), 3))
# RIGHT: split first; feature selection only ever sees the training rows
X_tr, X_te, y_tr, y_te = train_test_split(X, y, test_size=0.3, random_state=0, stratify=y)
honest = make_pipeline(SelectKBest(f_classif, k=20), LogisticRegression()).fit(X_tr, y_tr)
print("honest test accuracy: ", round(honest.score(X_te, y_te), 3))
# leaky test accuracy: 0.9
# honest test accuracy: 0.5
With 5,000 random features, some will correlate with the labels by pure chance, including on the test rows. Selecting features using all 100 rows picks exactly those, so the test rows have already voted. The Pipeline version fits the selection on training rows only, and the fantasy disappears. This is not a toy problem: genomics studies with thousands of genes and a few hundred patients have made exactly this mistake.
For time series, use scikit-learn's TimeSeriesSplit, or simply split on a date: train = df[df.date < "2024-01-01"].
Common pitfalls
- Peeking at the test set repeatedly. Every time you check the test score and change something, you leak a little information. After dozens of rounds, the test score is optimistic. Use the validation set or Cross-Validation for decisions, and keep the test set for the end.
- Preprocessing before splitting. Scaling, imputing, encoding, feature selection, oversampling of rare classes: fit all of them on training data only. Put them in a
Pipelineso it happens automatically. - Random splits on grouped or time-ordered data. Patients, users, documents, sessions, days: split by the unit you will generalise to.
- A test set that is too small to distinguish the models you are comparing. Compute the standard error before celebrating a 0.5% improvement.
- Throwing the split away at the end. After the final test, it is fine (and common) to retrain on all the data for deployment. Just report the test score from before you did.
Watch out If a result looks too good to be true, hunt for leakage before you celebrate. Sort features by importance and ask of the top few: could I really know this at prediction time? Most "breakthrough" scores on messy real-world data are leaks.
Where it leads
- Overfitting and the Bias–Variance Tradeoff: the gap between training and test performance, and what causes it.
- Cross-Validation: rotate the validation role through the data to get more reliable estimates from small datasets.
- Hyperparameter Tuning: the main consumer of validation data, and the main source of overfitting to it.
- Evaluation Metrics: what number to compute on the test set.
- Data Cleaning and Preparation: preprocessing that must respect the split.
- Time Series Forecasting: backtesting, the time-aware version of all of this.
- Evaluating LLMs and Benchmarks: the same problems at enormous scale, where benchmark questions leak into training data scraped from the web.
A bit of history
Statisticians have worried about judging a model on the data used to build it since at least the 1930s. The holdout method and its refinement, cross-validation, were developed in the 1960s and 1970s, notably by Mervyn Stone and Seymour Geisser, who in 1974–75 formalised assessing predictions on data left out of the fit. Machine learning made the three-way split routine. The Netflix Prize (2006–2009) and later Kaggle competitions popularised the public/private leaderboard: the competition's own hidden test set, revealed only at the end, which punished anyone who had overfitted to the public scores. In the era of large language models, the old problem has returned as benchmark contamination, where test questions are found in the web-scale training data.
Try it
- Rerun the decision-tree example with five different seeds in
default_rng. How much does the test accuracy move? What does that tell you about trusting a single split?- In the leakage example, change
k=20tok=200, then tok=2. How does the leaky accuracy change? Why?- You are predicting next week's sales for 50 shops from three years of daily data. Describe the split you would use, and name one feature that could leak.
Hint for 3: the model will be used to predict future weeks, possibly for shops it already knows. A feature computed over the whole three years (such as each shop's average sales) includes the future.
Learn more
Hand-picked courses, books, videos and tutorials for going deeper. See all resources →
MLU-Explain: Train, Test, and Validation Sets
An animated explainer of why and how to split data into training, validation and test sets.
Machine Learning Crash Course
Short, practical lessons with interactive visualisations covering regression, classification, embeddings and neural nets.
scikit-learn: Common Pitfalls and Recommended Practices
Short, concrete examples of data leakage, inconsistent preprocessing and randomness mistakes, and how pipelines prevent them.
An Introduction to Statistical Learning (with Python)
The friendliest rigorous introduction to classical ML, with Python labs. Free PDF.
Designing Machine Learning Systems
The practical guide to data, features, deployment, monitoring and iteration in production ML.
Kaggle Learn
Bite-sized interactive courses (Python, Pandas, intro ML, feature engineering) that run in the browser.
Facts checked as of 30 November 2026. Fast-moving details (products, prices, laws) change often. · Source: content/entries/ml/train-test-split.md