Train/Test Split, Done Right
Read a little, play a little. No scary maths, and no rush.
Exams need unseen questions
A student who memorizes past papers aces those papers and fails anything new. Models do exactly this — so we lock away part of the data as the test set, never touched during training or tuning, and judge exactly once at the end. That single number is the only honest estimate of real-world performance.
from sklearn.model_selection import train_test_split
Xtr, Xte, ytr, yte = train_test_split(
X, y, test_size=0.2, random_state=7, stratify=y
)
Standard recipes: 80/20, or 70/15/15 with a validation slice for tuning. Fix random_state so results reproduce exactly — "works on my machine" includes randomness.
Two refinements beginners miss
- Stratify. With 5% churners, a random split might put nearly none in test.
stratify=ypreserves class ratios on both sides — rare classes must be gradeable everywhere. - Time data splits by time. Predicting next month from past months? Random shuffling lets the model train on the future. Always split chronologically: past trains, future tests.
A worked example: fraud at 1%
A bank has 100,000 labeled transactions, and 1,000 of them are fraud.
- Stratify. An 80/20 stratified split puts about 200 frauds in the test set. Without stratifying you would still get roughly 200 on average, but any single split could come out noticeably higher or lower, and with rare classes that swing distorts the score.
- Respect time. Fraudsters change tactics, so a model trained on January to September and tested on October tells you how it will behave next month. A random split mixes October into training and flatters the result.
- Keep groups together. The same card appears in hundreds of transactions. If some land in training and others in test, the model can learn that card's habits and appear to detect fraud it is really just recognizing.
Group splits
When rows come in groups (many transactions per card, many visits per patient, many photos per person), every row from a group must sit on the same side of the split. scikit-learn provides GroupShuffleSplit and GroupKFold for this: you pass a group ID column, and it splits by group instead of by row.
Cross-validation in one line
from sklearn.model_selection import cross_val_score
scores = cross_val_score(model, Xtr, ytr, cv=5)
print(scores.mean(), scores.std())
Five train-and-validate rounds on the training data give five scores. Report the average and the spread: a model scoring 0.90 ± 0.01 is more trustworthy than one scoring 0.91 ± 0.06. The test set still stays locked away for the final check.
How big should the test set be?
Absolute counts matter more than percentages. Twenty percent of a million rows is far more test data than you need, while 20% of 500 rows may hold only a handful of the rare class you care about. Make sure the test set contains enough examples of every class, and every situation that matters, to measure them meaningfully.
Leakage: the 99% that lies
A churn model with a cancel_date feature scores 99% — because at prediction time that column doesn't exist yet. Duplicates straddling train/test, preprocessing fit on full data, future info in features: all the same crime. The defense is one question, asked relentlessly: "Would I know this value when actually predicting?"
Remember this
- Train learns, validation tunes, test judges once. Stratify classes, split time by time.
- Leakage turns metrics into fiction; the prediction-time question catches it.
Check your understanding
5 questions · first-try answers earn the most XP
My notes
Saved in this browser. Highlight a line above and save it, or write it in your own words.
Nothing saved yet. Your highlights will live here.
References
Finished reading?
Ticking it here also ticks the chapter in the sidebar, the section count and your streak — it is all one number.
Related chapters
Spotted a mistake or want a topic covered? Report an issue