How Machines Learn Guide 3 of 6 · tap to switch
Train Test Split (Train, Validation & Test)
How to test a machine learning model honestly without letting it cheat, peek at the exam, or leak future data.
Imagine you are studying for your driving theory exam using a booklet of 50 practice questions. After reading them ten times, you score 100%. Does that prove you are ready for unfamiliar questions on the real exam? That is exactly why every reliable model starts with a clean train test split (and a separate validation set).
Of course not. You might simply have memorized the answers in your booklet.
Machine learning models have the exact same problem. If you train a model on historical bank loan records and grade it on those same records, it can score 99% while failing completely on tomorrow’s real applicants. The cure is dividing your dataset into three separate jobs before you train anything:
- Training Set (The Study Booklet): Examples the model learns patterns from.
- Validation Set (Practice Exams): Unseen practice rounds used to compare models and adjust settings.
- Test Set (The Sealed Real Exam): Locked in a vault and opened once at the very end for one honest grade.
Play with the split sliders and dataset size below to feel the real tug-of-war between giving the model enough examples to learn and keeping enough locked away for a trustworthy grade.
Notice the surprise when you switch from Small (150 rows) to Large (10,000 rows). On 150 rows, keeping only 5% for testing leaves just 7 or 8 examples, making your test grade wobble by more than ±20% purely from luck. On 10,000 rows, even 10% puts 1,000 examples in the test vault, tightening that luck wobble down to ±2%. Absolute test count matters far more than a rigid percentage rule.
Train Test Split vs. Train, Validation & Test Splits
Beginners often ask: “If I already have a Train set and a Test set, why bother with a third Validation set?”
Because the moment you look at a Test score, tweak a setting, and re-test to see if the number went up, you have started fitting to that exam’s random quirks. Even if every candidate model has the exact same 80% real-world skill, trying 25 tweaks on the same reused exam and keeping whichever lucky guess scored highest will hand you a flattering mirage near 90%.
Click Try +5 Tweaks below to watch that illusion grow, then click Unlock Sealed Test Vault Once to see reality snap back into focus.
That widening red illusion gap is why disciplined teams treat the Test Set like a sealed medical trial envelope. Tune freely on the Validation Set, pick one winner, and open the Test Vault once to report the honest number.
Catching data leakage before it ruins production
Even with three clean splits, subtle mistakes can quietly smuggle answers from the Test Vault back into Training. This bug is called data leakage, and it creates models that look brilliant on your laptop and collapse the day real users touch them.
Before training, teams also often rescale (or normalize) number columns, shifting each value using the dataset’s average and spread so large numbers like annual income do not drown out smaller numbers like age. That everyday cleanup step turns into a sneaky leak if you run it before separating your splits.
Test the two most common real-world leaks below:
- Time-Travel Leak: Shuffling monthly cafe revenue randomly lets the model peek at next month to guess this month.
- Scaler-Before-Split Leak: Rescaling every row before splitting sneaks the test set’s average and extreme outliers straight into the training numbers.
Rule of thumb: split first, transform second. Any step that calculates summary numbers from your data (averages and spreads for rescaling, medians for filling missing cells, category rules, or feature selection) must learn those numbers from the Training Set only, then apply those frozen rules to Validation and Test.
When plain random splits break: rare events and groups
Randomly shuffling rows assumes every row is independent and every outcome is reasonably common. In real life, two common situations break that assumption fast.
First, rare events. Suppose you have 40 card transactions and only 4 are fraud (10%). In Plain Random Split mode below, a random draw can easily drop zero frauds into your Test Vault or crowd half of them into Test, leaving you blind to how well the model catches fraud. Click Reshuffle Split a few times to see random chance break the balance, then switch to Stratified Split (which preserves the exact rare-event ratio inside every split) to lock 10% fraud into both piles.
Second, grouped records that belong to the same person or entity. Imagine a hospital dataset with 10 X-ray scans per patient across 200 patients. If you shuffle all 2,000 individual scans and split them randomly, 7 scans of Patient A might land in Training while 3 scans of Patient A land in the Test Vault. Instead of learning to diagnose disease, the model can cheat by memorizing Patient A’s unique ribcage shape, jewelry shadow, or scanner tag, then recognize that exact same patient on the test scans. When brand-new patients arrive at the clinic tomorrow, the model fails.
The fix is a Group Split: bundle every row that shares an identity (all 10 scans from one patient, every order from one shopper, or every clip from one speaker) and place the entire group into either Training, Validation, or Test. That way, every patient in the Test Vault is truly someone the model has never seen before.
Before you shuffle, ask one question: Could the same person, device, or time window appear on both sides of the split? If yes, plain random shuffling leaks hidden clues. Use a Group Split for repeated people or entities, a Chronological Split for time-ordered records, and a Stratified Split for rare classes.
See the statistical theory, sample-size bounds & leakage taxonomyThesis / Reference
1. Empirical risk vs true generalization risk: A model is judged by its expected loss over the true unseen data distribution :
Because is unknown, an untouched i.i.d. test set of size provides an unbiased estimator .
2. Why absolute test size beats fixed ratios: For classification accuracy , the approximate 95% confidence interval half-width scales inversely with :
To cut evaluation uncertainty in half, you must quadruple . That is why 98/1/1 on a 1-million-row dataset (, ) is vastly more accurate than 70/15/15 on 200 rows (, ).
3. Adaptive holdout bias (winner’s curse): Selecting the best of models on a single finite validation set introduces positive selection bias scaling roughly as (see Dwork et al., 2015, The Reusable Holdout). Separating validation from a single-use test vault eliminates this bias from final reporting.
4. Three non-i.i.d. splitting rules (Kaufman et al., 2012): (a) Stratified splits preserve minority class prevalence; (b) Chronological / walk-forward splits enforce for temporal series; and (c) Group splits keep all rows from the same patient, user, or device in one split so the model cannot memorize individual identities.
See leak-free splitting in Python (scikit-learn)Optional Code
from sklearn.model_selection import train_test_split
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.linear_model import LogisticRegression
# 1. Split FIRST, preserving rare class ratios with stratify=y
X_temp, X_test, y_temp, y_test = train_test_split(
X, y, test_size=0.15, stratify=y, random_state=42
)
X_train, X_val, y_train, y_val = train_test_split(
X_temp, y_temp, test_size=0.176, stratify=y_temp, random_state=42
) # 70% train / 15% val / 15% test
# 2. Wrap scaler + model in a Pipeline so scaling fits on X_train ONLY
pipe = make_pipeline(StandardScaler(), LogisticRegression())
pipe.fit(X_train, y_train)
print("Validation accuracy:", round(pipe.score(X_val, y_val), 3))
# Open X_test ONCE after all tuning is finished:
print("Final Test accuracy:", round(pipe.score(X_test, y_test), 3))Four-point split checklist before you train
- Split first, transform second: Never rescale numbers, fill missing values, or rebalance rare classes before separating Train, Validation, and Test.
- Match split structure to real life: Use chronological splits for time series, group splits when multiple rows belong to one person or hospital, and stratified splits for rare classes.
- Never tune on the Test Vault: Tune on Validation (or Cross-Validation on smaller datasets), then unlock Test once.
- Watch the Train vs Validation gap: Next up in Overfitting and Underfitting, we see exactly what that gap reveals about whether your model actually learned the pattern or just memorized the noise.
Quick Intuition Check
Four quick real-world scenarios. No scores, just test your intuition.
A data scientist rescales all 5,000 customer incomes using the full dataset's average and spread first, then splits the rows 80/20 into train and test sets. What went wrong?
You want to forecast next month's grocery store demand using three years of daily sales records. Which split is honest?
A team tests 30 different model setups directly on their test set and reports the highest score (93%) to leadership. Why is 93% likely misleading?
If a hospital dataset has 10 X-ray scans per patient across 200 patients, randomly splitting individual scans 80/20 is safe.
Common Questions
Why can't I evaluate my machine learning model on the training set?
What is the difference between a validation set and a test set?
What split ratio should I use (70/15/15 vs 80/10/10 vs 98/1/1)?
What is data leakage in machine learning?
When should I use a stratified or chronological split instead of a random split?
Related Visual Guides
Cross-Validation & K-Fold Cross-Validation
How rotating every slice of your dataset through the exam seat turns lucky split roulette into a trustworthy score.
Overfitting vs Underfitting & Bias-Variance
How to tell real learning apart from blind memorization, understand the bias-variance tradeoff, and cure overfit models.
Feature Scaling: Normalization vs Standardization
Why salary in pounds bullies age in years, how Min-Max, Standardization, and RobustScaler compare under outliers, and which models actually care.
Written & illustrated by Muhammad Aashir Irshad · Updated December 2026 · Free open-access reference
Cite this guide in a paper, thesis, or course (BibTeX & APA)
@misc{irshad2026trainvalidationtestsplits,
author = {Irshad, Muhammad Aashir},
title = {Train Test Split (Train, Validation & Test): Interactive Visual Guide},
howpublished = {SeeingML},
year = {2026},
month = {dec},
url = {https://seeingml.com/learn/train-validation-test-splits/},
note = {Interactive visual guide}
} Irshad, M. A. (2026). Train Test Split (Train, Validation & Test): Interactive Visual Guide. SeeingML. https://seeingml.com/learn/train-validation-test-splits/