Lesson 6 of 13 · How Models Learn
Training and Testing Data
Why ML models are tested on unseen data: the train/test split, why memorising looks perfect but fails, validation sets and splitting with scikit-learn.
- 12 min read
- Beginner
- Reviewed
- Explain why a model must be tested on data it never saw in training
- Split a dataset into training and test sets
- See how a model that memorises can look perfect and still fail
- Know when to use a validation set as well
- Choose a setting with a validation set and cross-validation in scikit-learn
- Recognise the common kinds of data leakage and prevent them
The exam you've already seen
Imagine a teacher who hands out the exam questions as homework, then sets the very same questions in the exam. Every student who memorised the answers gets full marks, but the marks say nothing about what they understand.
Testing a model on its own training data has the same problem. So we keep some data aside.
A memoriser vs a real pattern
The program below creates 40 students (hours studied and exam score), shuffles them, and keeps 20% aside. It then compares two models: a memoriser that copies the score of the most similar training student, and a straight line that learns the general trend:
import random
random.seed(4)
# 40 students: hours studied -> exam score (a real pattern plus some luck)
students = []
for _ in range(40):
hours = round(random.uniform(0, 10), 1)
score = round(45 + 5 * hours + random.uniform(-8, 8))
students.append((hours, score))
# ---- Split: shuffle, then keep 20% aside for testing ----
random.shuffle(students)
cut = int(len(students) * 0.8)
train, test = students[:cut], students[cut:]
print(f"Training examples: {len(train)}, test examples: {len(test)}")
# ---- Model 1: "the memoriser" copies the score of the most similar training student ----
def memoriser(hours):
return min(train, key=lambda s: abs(s[0] - hours))[1]
# ---- Model 2: a straight line fitted to the training data ----
n = len(train)
mx = sum(h for h, s in train) / n
my = sum(s for h, s in train) / n
slope = sum((h - mx) * (s - my) for h, s in train) / sum((h - mx) ** 2 for h, s in train)
start = my - slope * mx
def line(hours):
return slope * hours + start
def mean_error(model, data):
return sum(abs(model(h) - s) for h, s in data) / len(data)
for name, model in [("memoriser", memoriser), ("straight line", line)]:
print(f"{name:<14} error on training data: {mean_error(model, train):4.1f} on test data: {mean_error(model, test):4.1f}")On the training data, the memoriser looks far better (an average error of 0.6 marks against 4.0). On the test data, the students it had never seen, it's worse than the straight line. It learned the noise in its particular students, not the pattern. Judged on training data alone, you'd have picked the wrong model.
How to split
- Shuffle first, so the test set isn't, say, all the newest examples or all from one region (unless that's what you want to test).
- Keep around 20% for testing (anything from 10% to 30% is common; more data allows a smaller share).
- Touch the test set once, at the end. If you keep adjusting the model until the test score looks good, the test set stops being unseen.
In scikit-learn, one line does the split:
from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)random_state fixes the shuffle, so you get the same split every time you run the code.
Validation sets
While building a model you try many settings, and you need a way to compare them without using up the test set.
A common split is 60% training, 20% validation, 20% test. When data is scarce, cross-validation reuses the data more efficiently: split it into, say, 5 parts, train 5 times, each time validating on a different part, and average the scores.
Here is the whole routine in scikit-learn. The model is k-nearest neighbours, which predicts by looking at the k most similar training examples; k is the hyperparameter to choose. (The next lesson explains scikit-learn models properly; here, watch which data each step uses.)
from sklearn.datasets import make_classification
from sklearn.model_selection import cross_val_score, train_test_split
from sklearn.neighbors import KNeighborsClassifier
X, y = make_classification(n_samples=500, n_features=8, random_state=0)
# 60% training, 20% validation, 20% test: split twice
X_train, X_rest, y_train, y_rest = train_test_split(X, y, test_size=0.4, random_state=42)
X_val, X_test, y_val, y_test = train_test_split(X_rest, y_rest, test_size=0.5, random_state=42)
print(f"train {len(X_train)}, validation {len(X_val)}, test {len(X_test)}")
# Compare settings on the validation set (the test set stays untouched)
scores = {}
for k in [1, 5, 15, 45]:
model = KNeighborsClassifier(n_neighbors=k).fit(X_train, y_train)
scores[k] = model.score(X_val, y_val)
print(f"k={k:<2} validation accuracy {scores[k]:.2f}")
best_k = max(scores, key=scores.get)
final = KNeighborsClassifier(n_neighbors=best_k).fit(X_train, y_train)
print(f"chosen k={best_k}, test accuracy {final.score(X_test, y_test):.2f} (measured once, at the end)")
# Cross-validation: 5 different validation folds from the training data
folds = cross_val_score(KNeighborsClassifier(n_neighbors=best_k), X_train, y_train, cv=5)
print("5-fold scores:", folds.round(2), " mean:", round(folds.mean(), 2))You should see 300, 100 and 100 rows, then validation accuracies of 0.81, 0.86, 0.81 and 0.82, so k = 5 wins. Its test accuracy is 0.79, a little lower than its validation score: picking the best of four settings on the same validation data flatters the winner slightly, which is exactly why the final check uses data nobody has looked at. The five cross-validation scores range from 0.78 to 0.85. Any single split can be lucky or unlucky, so their average (0.82) is a steadier estimate.
train_test_split has two more useful options: stratify=y keeps the share of each class the same on both sides (important when one class is rare), and shuffle=False keeps the original order, for data sorted by time.
Data leakage
The last two examples are cases of data leakage, which you met in Features and Labels: information that won't be available when the model is really used slips into training or evaluation. Leakage is the most common reason a model that tested brilliantly disappoints in real use, and it doesn't only come from features. Any route by which the test data can influence training is a leak.
| Kind of leak | What happens | Example |
|---|---|---|
| Target leakage | A feature is computed from the label, or recorded after it | “Cancellation reason” in a model predicting which customers will cancel |
| Train-test contamination | Data preparation (scaling, filling gaps, choosing features) uses all the rows, test rows included | Scaling with the average of the whole dataset before splitting |
| Time leakage | The model trains on data from after the period it's tested on | A random split of daily sales |
| Groups and duplicates | The same patient, customer or a near-identical row ends up on both sides | Several scans of one patient |
Train-test contamination is the easiest to miss, because the code looks reasonable. In the program below, the labels are coin flips, so no model can honestly do better than about 50%. The leaky version picks the 20 features most related to the labels using all the rows, then cross-validates. The honest version wraps the same two steps in a pipeline, so the feature choice is redone inside each training fold and never sees that fold's validation rows.
import numpy as np
from sklearn.feature_selection import SelectKBest
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import cross_val_score
from sklearn.pipeline import make_pipeline
rng = np.random.RandomState(0)
X = rng.normal(size=(100, 2000)) # 100 rows, 2,000 random features
y = rng.randint(0, 2, size=100) # random labels: there is nothing to learn
# Leaky: choose the 20 "best" features using ALL rows, then cross-validate
X_chosen = SelectKBest(k=20).fit_transform(X, y)
leaky = cross_val_score(LogisticRegression(), X_chosen, y, cv=5).mean()
# Correct: a pipeline repeats the selection inside each training fold
pipeline = make_pipeline(SelectKBest(k=20), LogisticRegression())
honest = cross_val_score(pipeline, X, y, cv=5).mean()
print(f"leaky accuracy: {leaky:.0%}")
print(f"honest accuracy: {honest:.0%}")The output is a leaky accuracy of 81% and an honest accuracy of 43%. Predicting coin flips with 81% accuracy is impossible: the feature selection had already seen the validation rows and kept the 20 features that matched their labels by chance. The honest 43% is close to guessing; with only 100 rows, scores near 50% wobble by several points either way.
How to prevent leakage:
- Split first, before any cleaning, scaling or feature selection, and fit those steps on the training set only. Putting them in a
Pipelinedoes this for you, including inside cross-validation. - Ask of every feature: would I have this value at the moment of prediction?
- Split by time for forecasts (
TimeSeriesSplitdoes this for cross-validation) and by group when one person or item has several rows (GroupShuffleSplit,GroupKFold). Remove duplicate rows before splitting. - Use the test set once. Choosing between models by their test scores leaks the test set into your decisions.
The scikit-learn guide to common pitfalls has more leakage examples, and the cross-validation guide covers time and group splits.
Common mistakes
Hold back a test set: split the shuffled examples 80/20.
# Examples that have already been shuffled
examples = ["e7", "e2", "e9", "e1", "e5", "e10", "e3", "e8", "e4", "e6"]
test_share = 0.2
# Put the first 80% in `train` and the last 20% in `test`, then print:
# Train: [...]
# Test: [...]
train = examples
test = []
print("Train:", train)
print("Test:", test)
Why do we keep a test set that the model never trains on?
You scale all 10,000 rows using their overall average, then split them into training and test sets. What's the problem?
Summary
- Split data into a training set to learn from and a test set to evaluate on.
- A model that memorises can look perfect on training data and still fail on new data.
- Shuffle, keep about 20% for testing, and use the test set once, at the end.
- Use a validation set or cross-validation (
cross_val_score) to choose settings, and split by time when predicting the future. - Data leakage (target leakage, train-test contamination, time leakage, groups and duplicates) makes scores too good to be true. Split first and keep preparation inside a Pipeline.
Next: train your first real model with scikit-learn.
Finished reading? Tick it off to track your progress.