SeeingML
How Machines Learn Guide 3 of 6 · tap to switch
✦ Interactive Visual Guide 8 min · 4 hands-on labs · Beginner friendly

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.

Interactive Lab 1: Split Ratios & Score Reliability
Train: 70% (105)Validation: 15% (23)Test Vault: 15% (22)
Each square shows 1% of your rows. Click Reshuffle Split to see different rows move into Train, Validation, and Test.
Quick presets:
Model True Skill
87%
Driven by training rows
Measured Test Score
86%
Single draw from Test Vault
Test Score Uncertainty
±14%
Typical luck wobble
Where a single test draw can land (50% to 100% scale)True: 87% | Draw #1: 86%
50%75%100%
70%
15%
Balanced split on 150 rows: 105 rows to learn (87% true skill), 23 to tune, and 22 locked in the Test Vault (±14% luck wobble; Draw #1 scored 86%).

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.

Interactive Lab 2: Why Reusing the Test Set Creates a Mirage
Models tried: 1/25
Best reused exam score (76%)Each individual tweak's noisy scoreReal unseen accuracy (80%)Illusion gap (0%)
75%80%85%90%95%#1#5#10#15#20#25Number of Model Tweaks Checked on the Same Reused Exam
Step 1: Try several tweaks on the reused exam. Step 2: Unlock the Sealed Test Vault once to check reality.
After 1 model try, your reused exam score (76%) sits right near real unseen accuracy (80%). Step 1: Click "Try +5 Tweaks" to watch what happens when you keep tuning against the same practice exam.

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:

  1. Time-Travel Leak: Shuffling monthly cafe revenue randomly lets the model peek at next month to guess this month.
  2. Scaler-Before-Split Leak: Rescaling every row before splitting sneaks the test set’s average and extreme outliers straight into the training numbers.
Interactive Lab 3: Catch the Two Sneakiest Data Leaks
Reported score: 96% (Mirage!)
Training monthsTest months (trapped between past & future)Time-travel peek at neighboring future month
$20k$30k$40k$50k$60kJan Y1Jun Y1Dec Y1Jun Y2Dec Y224 Months of Cafe Monthly Revenue
Cheating with time travel! Because test months (amber) sit between training months from both the past and the future, the model simply averages yesterday and tomorrow to score a fake 96%. Click "Honest: Past Train → Future Test" to fix the leak.

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.

Interactive Lab 4: Rare Events Need Stratified Splits
Tile key:! = Fraud (4 total)· = Safe (36 total)
True rate: 10% fraud
Training Set (30 records)Frauds: 4 (13%)
Test Vault (10)Frauds: 0 (0%)
Original dataset: 4 frauds out of 40 transactions (10% true rate)
Uh oh! This random draw put ZERO frauds in the Test Vault (0%). Your test exam cannot even check whether the model catches fraud! Switch to Stratified Split or click Reshuffle Split.

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.

⚠️ Warning

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 hh is judged by its expected loss over the true unseen data distribution D\mathcal{D}:

R(h)=E(x,y)∼D ⁣[ ℓ(h(x),y) ]R(h) = \mathbb{E}_{(x, y) \sim \mathcal{D}}\!\left[\,\ell(h(x), y)\,\right]

Because D\mathcal{D} is unknown, an untouched i.i.d. test set StestS_{\text{test}} of size ntestn_{\text{test}} provides an unbiased estimator R^test(h)=1ntest∑(x,y)∈Stestℓ(h(x),y)\hat{R}_{\text{test}}(h) = \frac{1}{n_{\text{test}}}\sum_{(x,y)\in S_{\text{test}}}\ell(h(x), y).

2. Why absolute test size beats fixed ratios: For classification accuracy p^\hat{p}, the approximate 95% confidence interval half-width scales inversely with ntest\sqrt{n_{\text{test}}}:

MOE95%≈1.96p^(1−p^)ntest\text{MOE}_{95\%} \approx 1.96 \sqrt{\frac{\hat{p}(1 - \hat{p})}{n_{\text{test}}}}

To cut evaluation uncertainty in half, you must quadruple ntestn_{\text{test}}. That is why 98/1/1 on a 1-million-row dataset (ntest=10,000n_{\text{test}} = 10{,}000, MOE<1%\text{MOE} < 1\%) is vastly more accurate than 70/15/15 on 200 rows (ntest=30n_{\text{test}} = 30, MOE≈14%\text{MOE} \approx 14\%).

3. Adaptive holdout bias (winner’s curse): Selecting the best of MM models on a single finite validation set introduces positive selection bias scaling roughly as O ⁣(ln⁡Mnval)O\!\left(\sqrt{\frac{\ln M}{n_{\text{val}}}}\right) (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 ttrain<tval<ttestt_{\text{train}} < t_{\text{val}} < t_{\text{test}} 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
python
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

  1. Split first, transform second: Never rescale numbers, fill missing values, or rebalance rare classes before separating Train, Validation, and Test.
  2. 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.
  3. Never tune on the Test Vault: Tune on Validation (or Cross-Validation on smaller datasets), then unlock Test once.
  4. 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.
✓ Self-Check

Quick Intuition Check

Four quick real-world scenarios. No scores, just test your intuition.

1

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?

Pick an option first, or peek anytime
2

You want to forecast next month's grocery store demand using three years of daily sales records. Which split is honest?

Pick an option first, or peek anytime
3

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?

Pick an option first, or peek anytime
4

If a hospital dataset has 10 X-ray scans per patient across 200 patients, randomly splitting individual scans 80/20 is safe.

Pick an option first, or peek anytime
Quick Reference

Common Questions

Why can't I evaluate my machine learning model on the training set?
Because the model adjusted its internal knobs directly on those examples. Scoring it on training data only measures how well it memorized past answers, not whether it can handle fresh unseen users in production.
What is the difference between a validation set and a test set?
You use the validation set repeatedly while comparing models and tuning settings. You lock the test set away and open it exactly once at the very end for an unbiased final grade. Reusing the test set to make tuning choices quietly turns it into a validation set.
What split ratio should I use (70/15/15 vs 80/10/10 vs 98/1/1)?
Absolute sample count matters more than fixed percentages. On 1,000 to 20,000 rows, 70/15/15 or 80/10/10 gives enough training data while keeping test uncertainty tight. On 1,000,000 rows, even 98/1/1 puts 10,000 rows in validation and test. On tiny datasets under 500 rows, use cross-validation instead of a single validation split.
What is data leakage in machine learning?
Data leakage happens whenever information from validation or test examples slips into training. Common examples include fitting a scaler or imputer before splitting, shuffling time-ordered data randomly so future days leak into past predictions, or letting the same patient appear in both train and test.
When should I use a stratified or chronological split instead of a random split?
Use a stratified split whenever one class is rare (such as 1% to 15% fraud or disease) so every split preserves the true class ratio. Use a chronological split for time-ordered data like sales forecasts, where training must strictly come from the past and testing from the future.

Written & illustrated by Muhammad Aashir Irshad · Updated December 2026 · Free open-access reference

https://seeingml.com/learn/train-validation-test-splits/ Open GitHub issue Suggest an edit
Cite this guide in a paper, thesis, or course (BibTeX & APA)
BibTeX
@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}
}
APA

Irshad, M. A. (2026). Train Test Split (Train, Validation & Test): Interactive Visual Guide. SeeingML. https://seeingml.com/learn/train-validation-test-splits/