Module 3 · Beginner · Data preparation and EDA

Train, validation and test sets explained

Why machine learning splits data into train, validation and test sets, how to split with scikit-learn, split sizes, stratifying, time splits and leakage.

By theprogrammers team · · 12 min read

A machine learning model is only useful if it works on new data it has never seen: next month's customers, tomorrow's emails, a house that isn't on the market yet. But you only have the data you already have. The solution is to hide part of it from the model during training, then use that hidden part to check how well the model really performs.

That's what train, validation and test sets are for. The training set teaches the model, the validation set helps you choose between models, and the test set gives one honest final score. Below: why each exists, how to split with scikit-learn, what sizes to use, stratification, time series, and the mistakes that make results look better than they are.

What you need first: the scikit-learn tutorial, for fit, score and train_test_split, and the machine learning workflow.

Key terms

  • Training set: the rows the model learns from.
  • Validation set: rows held back to compare models and choose settings during development.
  • Test set: rows held back until the very end, used once for the final score.
  • Stratify: split so each part keeps the same share of each class as the whole dataset.
  • Data leakage: information from outside the training data, such as test rows or the future, sneaking into training.

Why not test on the training data?

Imagine a student who gets the exam questions in advance and memorises the answers. They'd score 100%, but that score says nothing about whether they understand the subject. A model evaluated on its own training data is that student.

This lesson uses the Spambase data: 4,601 emails described by 57 word and character frequencies, each labelled spam (1) or not spam (0).

Download the data: spambase.csv (1.1 MB), or from the original source, the UCI Machine Learning Repository. The code below loads it for you, so you only need the file to open it in a spreadsheet or work offline: load it with pd.read_csv("spambase.csv").

import numpy as np
from sklearn.datasets import fetch_openml
from sklearn.tree import DecisionTreeClassifier
from sklearn.model_selection import train_test_split

X, y = fetch_openml(data_id=44, as_frame=True, return_X_y=True)   # Spambase
X, y = X.to_numpy(), y.astype(int).to_numpy()                     # 1 = spam, 0 = not spam

model = DecisionTreeClassifier(random_state=0).fit(X, y)
print("Accuracy on the data it trained on:", round(model.score(X, y), 3))
Accuracy on the data it trained on: 0.999
  • X.to_numpy() turns the pandas table into a plain NumPy array; y.astype(int) turns the labels from the text "0"/"1" into numbers.
  • DecisionTreeClassifier builds a flowchart of yes/no questions about the features. random_state=0 fixes the small amount of randomness in how it breaks ties.

A near-perfect score, and a meaningless one: a decision tree can memorise almost every training example. (It isn't quite 100% because a few emails have exactly the same 57 numbers but different labels, so no model can get both right.) The machine learning workflow uses the same data.

Split into training and test sets

train_test_split shuffles the rows and splits them. Predict first: the tree scored 0.999 on data it had seen. Roughly what will it score on 921 emails it hasn't?

X_train, X_test, y_train, y_test = train_test_split(
    X, y, test_size=0.2, random_state=42)
print(X_train.shape, X_test.shape)

model = DecisionTreeClassifier(random_state=0).fit(X_train, y_train)
print("Train accuracy:", round(model.score(X_train, y_train), 3))
print("Test accuracy: ", round(model.score(X_test, y_test), 3))
(3680, 57) (921, 57)
Train accuracy: 0.999
Test accuracy:  0.914
  • test_size=0.2 keeps 20% of rows back for testing.
  • random_state=42 makes the shuffle repeatable, so you get the same split every run.
  • It returns four pieces in a fixed order: train features, test features, train labels, test labels.

The test accuracy, 91.4%, is the honest estimate of how the model will do on new emails. The gap between 99.9% and 91.4% is a sign of overfitting: the model learnt some details of the training emails that don't hold for new ones. The next module has a full lesson on overfitting and underfitting.

Why a validation set too?

You rarely train only one model. You try different algorithms and settings, such as how deep a decision tree may grow, and pick the best. If you pick the best by test score, the test set has quietly become part of training: you've chosen the model that happens to suit those particular rows. Its score is now too optimistic.

So use three sets, each with one job:

SetUsed forTypical share
TrainingFitting the model's parameters60–80%
ValidationComparing models and choosing settings10–20%
TestOne final, honest score at the very end10–20%

The test set is like a sealed final exam: you open it once.

Make a train, validation and test split

Call train_test_split twice: first set aside the test set, then split what's left:

X_temp, X_test, y_temp, y_test = train_test_split(
    X, y, test_size=0.2, random_state=42)
X_train, X_val, y_train, y_val = train_test_split(
    X_temp, y_temp, test_size=0.25, random_state=42)
print(len(X_train), len(X_val), len(X_test))
2760 920 921

0.25 of the remaining 80% is 20% of the total, so this is a 60/20/20 split.

A bar split into three parts: training, 60% or 2,760 rows, where the model learns; validation, 20% or 920 rows, used to compare models and pick settings; and test, 20% or 921 rows, the final exam used once.

Think of the three parts as homework, mock exams and the final exam. The model learns from the homework, you use the mock exams to choose between approaches, and the final exam is sat once.

Now choose a setting using the validation set only:

for depth in [2, 3, 4, 6, None]:
    model = DecisionTreeClassifier(max_depth=depth, random_state=0)
    model.fit(X_train, y_train)
    print(depth, round(model.score(X_val, y_val), 3))
2 0.87
3 0.875
4 0.897
6 0.905
None 0.904

max_depth limits how many questions deep the tree can go; None means no limit, so it keeps splitting until it has memorised the training rows.

Depth 6 scores best on the validation set, 0.905, just ahead of unlimited depth at 0.904. When scores are this close, choose the simpler model anyway: depth 6. Then retrain it and check it once on the test set:

best = DecisionTreeClassifier(max_depth=6, random_state=0).fit(X_temp, y_temp)
print("Final test accuracy:", round(best.score(X_test, y_test), 3))
Final test accuracy: 0.916

Retraining on training plus validation data (X_temp) gives the final model a little more data to learn from. The test score is what you report.

With small datasets, a single validation set is a noisy judge, since a few lucky rows can change the winner. Cross-validation fixes this by rotating the validation role across several folds; cross-validation explained, two modules on, covers it.

Stratify for classification

When one class is rare, a random split can leave the test set with too few examples of it. stratify=y keeps the class proportions the same in every split:

_, _, _, y_test_random = train_test_split(X, y, test_size=0.1, random_state=7)
_, _, _, y_test_strat = train_test_split(X, y, test_size=0.1, random_state=7, stratify=y)

print("Whole dataset: ", round(y.mean(), 3))
print("Random test:   ", round(y_test_random.mean(), 3))
print("Stratified test:", round(y_test_strat.mean(), 3))
Whole dataset:  0.394
Random test:    0.401
Stratified test: 0.395

The numbers are the share of spam (label 1). The stratified split matches the whole dataset almost exactly; the random one is off by less than a point. With 39% spam, a random split is rarely far wrong. With rare classes, such as 1% fraud, a random test set could easily contain half or double the real share, so stratifying is essential. Use it for every classification split.

Experiment: check that claim. Make 2,000 made-up payments of which about 1% are fraud, then split off a 10% test set with five different random seeds, with and without stratifying. Predict first: how many frauds will each test set get?

rng_fraud = np.random.default_rng(0)
fraud = (rng_fraud.random(2000) < 0.01).astype(int)
print("frauds in all 2,000 payments:", fraud.sum())
for seed in range(5):
    _, _, _, random_test = train_test_split(fraud, fraud, test_size=0.1, random_state=seed)
    _, _, _, strat_test = train_test_split(fraud, fraud, test_size=0.1, random_state=seed, stratify=fraud)
    print(f"seed {seed}: frauds in the random test set {random_test.sum()}, in the stratified one {strat_test.sum()}")
frauds in all 2,000 payments: 28
seed 0: frauds in the random test set 4, in the stratified one 3
seed 1: frauds in the random test set 1, in the stratified one 3
seed 2: frauds in the random test set 2, in the stratified one 3
seed 3: frauds in the random test set 0, in the stratified one 3
seed 4: frauds in the random test set 2, in the stratified one 3

The labels are passed twice because train_test_split needs features and labels; the made-up data has no features, so the labels stand in for both. The 2,000 payments contain 28 frauds, so a fair 10% test set should hold about 3. Every stratified split gets exactly 3. The random splits get anything from 0 to 4, and with seed 3 the test set has no frauds at all, so it couldn't tell you anything about how well a model catches fraud. That's why stratifying matters for rare classes.

Time series: don't shuffle

If rows are ordered in time, such as daily sales or monthly prices, a random split lets the model learn from the future to predict the past. In real use you only ever have the past. Split by time instead:

import pandas as pd

days = pd.DataFrame({"date": pd.date_range("2026-01-01", periods=10),
                     "sales": [12, 15, 14, 18, 20, 19, 23, 25, 24, 28]})
cutoff = int(len(days) * 0.8)
train, test = days.iloc[:cutoff], days.iloc[cutoff:]
print(train["date"].max().date(), "|", test["date"].min().date())
2026-01-08 | 2026-01-09

Every training date comes before every test date, just like in production.

Mistakes that leak information

Data leakage, later in this module, covers this with real examples. In short, data leakage happens when information from the test set sneaks into training. Results look great and then fail in real use. Common causes:

MistakeWhy it leaksFix
Scaling or filling missing values on all data before splittingTest statistics shape the training dataSplit first; fit transformations on training data only (pipelines do this for you)
Tuning on the test setThe test set becomes training dataUse a validation set or cross-validation
Random split of time seriesThe model sees the futureSplit by time
The same person, house or patient in train and testThe model recognises them instead of generalisingSplit by group (GroupShuffleSplit)
Duplicate rows across splitsThe test answers are in the training dataRemove duplicates first

Practice

  1. Split X, y into 70% training and 30% test, stratified, with random_state=0, and print the sizes.
Show the answer
X_tr, X_te, y_tr, y_te = train_test_split(X, y, test_size=0.3, stratify=y, random_state=0)
print(len(X_tr), len(X_te))
3220 1381

30% of 4,601 is 1,380.3, and scikit-learn rounds the test size up.

  1. Predict, then check: use the 60/20/20 split from above and score a tree with max_depth=1 (a single question) on the validation set. Will it beat the baseline of always saying "not spam" (about 61%)?
Show the answer
stump = DecisionTreeClassifier(max_depth=1, random_state=0).fit(X_train, y_train)
print(round(stump.score(X_val, y_val), 3))
0.797

Yes, clearly: 0.797 against about 0.61. One well-chosen question about the email already separates most spam from most real mail. But it's well below depth 6 (0.905), so it's underfitting: too simple to capture the patterns.

  1. Your model scores 99% on training data and 71% on test data. What does that suggest?
Show the answer

Overfitting: the model memorised the training data. Try a simpler model, regularisation, more data or fewer features, and compare options on a validation set.

  1. You have three years of daily sales. How would you choose the test set?
Show the answer

Use the most recent period, for example the last three months, as the test set, and train on everything before it. Never shuffle time series before splitting.

  1. A colleague tries 50 settings, picks the one with the best test score, and reports that score. Why is it too optimistic, and what should they have done?
Show the answer

With 50 tries, some setting will do well on those particular test rows partly by luck, and picking it bakes that luck into the reported score. They should choose the setting on a validation set (or with cross-validation), then score the chosen model once on the test set.

  1. A hospital dataset has several scans per patient. Why is a plain random split a problem?
Show the answer

Scans of the same patient can land in both training and test sets, so the model can score well by recognising the patient rather than the disease. Split by patient (for example with GroupShuffleSplit), so each patient's scans are all in one set.

Interview questions

What is the difference between a validation set and a test set?

The validation set is used during development to compare models and tune hyperparameters. The test set is used once, at the end, to estimate performance on unseen data. Using the test set for decisions makes its score optimistic.

What does stratify do in train_test_split?

It keeps the proportion of each class the same in every split as in the full dataset, which matters most when classes are imbalanced.

What is data leakage?

When information that wouldn't be available at prediction time, often from the test set, influences training. Examples include preprocessing before splitting, tuning on the test set, and random splits of time-series data. It makes evaluation scores misleadingly high.

Key takeaways

  • Never judge a model on the data it trained on: it can memorise.
  • Training data teaches the model, validation data chooses between models, and the test set is used once at the end.
  • A common split is 60/20/20; call train_test_split twice to make it.
  • Use stratify=y for every classification split, and split time series by date, never at random.
  • Leakage (preprocessing before splitting, tuning on the test set, shared people or duplicates) makes scores look better than they are.

Frequently asked questions

What is a good train/test split ratio?

80/20 is a common default, and 60/20/20 when you also need a validation set. With very large datasets the test share can be much smaller, such as 1%, because even 1% is plenty of rows for a stable score.

Do I need a validation set if I use cross-validation?

No. Cross-validation does the validation set's job by rotating it through the training data. You still keep a separate test set for the final score.

What does random_state do in train_test_split?

It fixes the random shuffle, so the same rows go to the same set on every run. Any number works; changing it gives a different, equally valid split.

What to learn next

  1. Fill in blanks before training in missing value imputation explained, the next lesson.
  2. Learn the more reliable alternative to one validation set in cross-validation explained.
  3. Revisit the machine learning workflow.