You hold back some data, train on the rest, and test on what you held back. The test score is supposed to tell you how the model will do on data it has never seen. It only can if the test rows really are unseen, and there are quiet ways for them not to be. When something about the test set leaks into training, the score goes up and the model doesn’t get any better. Split first, then do everything else using the training rows only. Here you’ll get 82% accuracy out of pure noise, watch a model recognise people instead of learning anything, and learn the checks that catch both.
The rule#
A train/test split divides your rows into a training set, which the model learns from, and a test set, which you use once at the end to measure it. In scikit-learn that’s one line:
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, stratify=y, random_state=42)stratify=y keeps the same mix of labels on both sides, which matters when one label is rare; random_state makes the split the same every time you run it. The hard part isn’t the line. It’s making sure nothing that happens afterwards peeks at the test rows: not the model, not the scaling, not the choice of which columns to use.
Choosing columns before you split#
Say you have far more columns than rows, as in genetics, text or sensor data. A common first step is to keep only the columns most related to the label. It feels like tidying, not training. Here’s what happens when you do it before splitting, on data where no column is related to the label at all.
Predict first
200 rows, 5,000 columns of random numbers, and labels from a coin flip. You keep the 20 columns most related to the label, using all 200 rows. Then you train on 140 rows and test on the other 60. What’s the test accuracy?
Look at the bars. Choosing with all 200 rows, every chosen column also leans the right way on the test rows (20 of 20 on the first draw): of course it does, those rows helped choose it. Choosing with the training rows only, about half lean the right way, which is what chance gives, and the accuracy falls to 48%: a coin flip, which is the truth.
More columns make it worse. With 100 columns the leak adds about 14 points; with 5,000, about 32, because the more columns you search, the better the best-looking accident looks. This exact mistake is a textbook example (“The wrong and right way to do cross-validation” in The Elements of Statistical Learning), and it still turns up in published research. Any step that looks at the labels is part of training, even if it doesn’t feel like it.
The same person on both sides#
Many datasets have several rows from one source: five recordings of each patient’s voice, a year of purchases from each customer, a dozen photos of each product. Rows from the same source look alike, because people and things are consistent. A random split sends some of each person’s rows to training and some to testing.
Predict first
Each of 60 people has 5 rows. A model tested on a random quarter of the rows scores 96%. You split again so that each person’s rows all go to the same side. What does it score now?
Split rows at random and almost every test ring is joined to a dot a hair’s width away: the same person’s other row. That scores 96% on the first split and 91% to 99% on most. Split by whole people and the lines reach across to someone else, and accuracy drops to 63% (44% to 73% on most splits). That’s the honest score, because when you use the model, every person will be new. Notice the range is wider too: with 15 people in the test set, you’re really testing on 15 examples, not 75.
This has happened in medical research. In 2017, researchers looking at studies that predict health from phones and wearable sensors (Saeb and others, in GigaScience) found that splitting recordings rather than people was common, and showed with real data that it can make accuracy look far higher than it is. Split by whatever the model will meet fresh in real use: new people, new customers, new days. In scikit-learn that’s GroupShuffleSplit or GroupKFold with a column saying who each row belongs to.
Three more ways the future leaks in#
- Time. If you’ll predict next month from this month, test on the latest data and train on everything before it. A random split lets the model see the future (see the forecasting explainer below).
- Columns from after the fact. A column filled in after the outcome, such as “refund issued” when predicting complaints or “length of stay” when predicting hospital admission, makes a model look brilliant and useless. For every column, ask: would I know this at the moment I need the prediction?
- Duplicates. The same email forwarded twice, the same photo resized: one copy in training and one in testing is the same-person problem in its purest form. Remove near-duplicates before you split.
And use the test set once. Every time you peek at it and adjust something, it becomes a little more like training data. Tune on a separate validation set or with cross-validation, and keep the test set for the final check.
In code#
The first figure’s mistake and its fix, in scikit-learn:
import numpy as np
from sklearn.feature_selection import SelectKBest, f_classif
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import cross_val_score
from sklearn.pipeline import make_pipeline
rng = np.random.default_rng(0)
X = rng.normal(size=(200, 5000)) # 5,000 columns of pure noise
y = rng.integers(0, 2, size=200) # coin-flip labels
# Wrong: choose the columns using every row, then cross-validate
X_chosen = SelectKBest(f_classif, k=20).fit_transform(X, y)
print("chosen first:", cross_val_score(LogisticRegression(), X_chosen, y, cv=5).mean().round(2))
# Right: the choosing happens inside each training fold
pipe = make_pipeline(SelectKBest(f_classif, k=20), LogisticRegression())
print("inside the pipeline:", cross_val_score(pipe, X, y, cv=5).mean().round(2))
# chosen first: 0.8
# inside the pipeline: 0.51And the second figure’s, continuing the same script, with a column saying which person each row came from:
from sklearn.model_selection import GroupKFold, KFold
from sklearn.neighbors import KNeighborsClassifier
person = np.repeat(np.arange(60), 5) # 60 people, 5 rows each
centre = rng.uniform(-1, 1, size=(60, 2))
label = (rng.random(60) < 1 / (1 + np.exp(-2.5 * centre[:, 0]))).astype(int)
X = centre[person] + rng.normal(0, 0.04, size=(300, 2))
y = label[person]
model = KNeighborsClassifier(n_neighbors=1)
print("rows at random:", cross_val_score(model, X, y, cv=KFold(4, shuffle=True, random_state=0)).mean().round(2))
print("whole people: ", cross_val_score(model, X, y, cv=GroupKFold(4), groups=person).mean().round(2))
# rows at random: 0.86
# whole people: 0.46What to remember
- A test score is honest only if nothing about the test rows reached training, including scaling, filling blanks and choosing columns.
- Choosing columns with all the data can turn pure noise into 80% accuracy; fit every step inside a Pipeline on the training rows.
- When rows come in groups (people, customers, days), split by group, because that’s what the model will meet in real use.