Interview's MateData Science
Interview's Mate

Data Science

Python → ML → MLOps

Visualizer

DSA Visualizer
All 32 lessons
Custom Playground
Try your own examples

Learning

System Design
31 architecture topics
SQL Learning
160 foundations → production topics
AI Engineering
160 LLM → backend topics
Data Science
160 Python → MLOps topics
Data Engineer
160 SQL → streaming topics
Docker
160 Docker learning topics
Kubernetes
160 K8s fundamentals → cloud
Java LearnSoon
Coming soon
Python Learn
Interview Q&A & internals
JavaScript Learn
Closures, async & DOM Q&A
Tech Learn
Search, practise & track Q&A
AI DSA Practice
Solve coding problems
Theme
Home
Data Science topics
Lesson 82/ 160
05. Classical Machine Learning

Train-Validation-Test Splits & Data Leakage

Split data honestly and prevent leakage from preprocessing, targets, and time.

BeginnerHoldout · Leakage · Honest Eval3 quiz questions
Practice Generative AI Q&A
In plain wordsDiagramTheoryStep by stepWhen to use itInterview cluesMistakes to avoidQuiz (3)Practice

In plain words

Keep some data completely hidden until the end, and never let the model peek at information it wouldn't really have when making a prediction.

Think of it like…

A student who sees the exam questions while studying will ace the practice test and fail the real one; the test set is the sealed exam, and leakage is any way the answers sneak into the study materials.

Where you’ve seen it

A loan-default model scores AUC 0.99 in validation. Inspection shows a feature collections_calls_last_90d, recorded after the borrower defaulted: it is target leakage. Removing it drops AUC to 0.78, the honest figure. A second model uses StandardScaler fitted on the full dataset before splitting, leaking test means and variances (a small effect, but it also contaminates cross-validation); the fix is a scikit-learn Pipeline so scaling is fit inside each training fold. A third issue: each customer has 5 records, and a random 80/20 record split puts a customer's other records in training for 1 − 0.2⁴ = 99.84% of test rows, so the model memorises customers; a GroupKFold by customer id removes it. Finally, because deployment predicts next month, the final split is temporal: train on months 1 to 9, validate on month 10, test on months 11 and 12. With 1,000 test rows and 90% accuracy, the standard error is √(0.9 × 0.1 / 1000) = 0.95 points, so the 95% interval is about ±1.9 points.

Words you’ll hear

Train / validation / test
Data for fitting, for choosing models and for a final unbiased estimate.
Target leakage
A feature that contains or is derived from the outcome or information unavailable at prediction time.
Preprocessing leakage
Fitting scalers, imputers or encoders on data that includes validation or test rows.
Group / temporal split
Splitting by entity or by time so related or future rows don't cross the boundary.

Visual diagram

Loading interactive diagram

Theory & deep dive

Designing splits that match deployment

Use a three-way split (for example 70/15/15) or k-fold cross-validation on the training portion with a final held-out test set. Stratify on the label so rare classes appear in every split (train_test_split(..., stratify=y)). If rows are grouped (several records per customer, patient, device, session), keep each group entirely on one side (GroupKFold, GroupShuffleSplit); otherwise the model memorises entities, as the 99.84% sibling-leak calculation shows. For time-ordered data, split by time (train on the past, evaluate on the future) and use rolling-origin validation (TimeSeriesSplit); random splits let the model learn from the future.

Pick sizes so the test estimate is precise enough: the standard error of an accuracy p over n rows is √(p(1 − p)/n); for p = 0.9 and n = 1,000 it is 0.95 points (95% interval ±1.9), but for a rare-class recall estimated from 40 positives it is far wider. Use repeated or nested cross-validation when data is small, and report the interval, not just the point estimate. Keep the test set sealed: each look at it and subsequent tweak turns it into another validation set, leaking selection bias.

Group leakage arithmetic

5 records per customer, random 80/20 record split. A test record's four siblings are all in the test side with probability 0.2⁴ = 0.16%, so 99.84% of test rows have at least one sibling in training. A model that memorises customer-specific patterns looks great and fails on new customers.

Key takeaway: Split by the unit and the time order of deployment, stratify, size the test set for the precision you need and seal it.

Common leaks and how to prevent them

Target leakage: features created from the outcome (a refund flag when predicting returns, post-outcome collections calls, an invoice status updated after payment). Test by asking for each feature "is this known at prediction time?", and look for suspiciously strong single features (one feature with AUC 0.95 is a red flag). Preprocessing leakage: imputation, scaling, PCA, target encoding, feature selection and resampling (SMOTE) must be fit on training data only; put them in a Pipeline, and run cross-validation over the whole pipeline. Applying SMOTE before splitting leaks synthetic neighbours of test points into training.

Further leaks: duplicates and near-duplicates across splits (de-duplicate before splitting, or group them); temporal leakage (rolling features computed with future rows, a global mean over the whole period); label leakage through IDs or ordering (sorted files where position encodes the label); hyperparameter overfitting to a small validation set (use nested CV); and leakage via the test set during exploration (looking at test distributions to engineer features). Defences: a clear data-availability timeline for each feature, automated tests (fail the build if a feature appears in the leakage allow-list), baseline sanity checks (a model with shuffled labels should score at chance), and monitoring production against offline performance to catch silent gaps.

Pipeline instead of manual scaling

pipe = make_pipeline(SimpleImputer(), StandardScaler(), LogisticRegression()) then cross_val_score(pipe, X, y, cv=GroupKFold(5), groups=customer_id). Each fold fits the imputer and scaler on its own training portion only, so no validation statistics leak into the fit.

Key takeaway: Check every feature's availability, fit all preprocessing inside the training fold and test with shuffled labels and production monitoring.

How it works, step by step

Step 1 of 4
Analyst

1. Define the prediction moment

Write when the model will predict and which data is available at that time.

predict next month from data up to today
Key numbers at this step
Feature
availability timeline

When to use it & trade-offs

What it is

Honest evaluation separates data into a training set (fit parameters), a validation set or cross-validation folds (choose models and hyperparameters) and a test set (one final, untouched estimate of real-world performance). Data leakage is any path by which information from the validation or test data, or from the future or the target, reaches the model during training: preprocessing fitted on all data, features computed after the outcome, duplicate or related rows on both sides of a split, or time travel. Leakage makes offline scores look excellent and production results disappointing, which is why preventing it is more important than any algorithm choice.

Why it matters: A leaked model can report 0.99 AUC in notebook and 0.7 in production, after the business has already planned around it. Most spectacular failures in applied ML trace back to leakage or an evaluation that didn't match deployment (random split on time-ordered data, row-level split on customer-level data). Designing the split to mirror how the model will be used is the core of trustworthy evaluation.

When to reach for it

  • Every supervised modelling project
  • Debugging models that fail after deployment
  • Reviewing others' notebooks for suspiciously high scores

When to avoid or be careful

  • Fitting scalers or imputers before splitting
  • Random splits on time-ordered or grouped data
  • Tuning repeatedly against the test set

Split strategies

Random stratified split
Best for: Independent rows with no time or group structure

Strengths: Simple; preserves class balance.

Watch out: Leaks when rows are related or time-ordered.

Group split or GroupKFold
Best for: Multiple rows per customer, patient or device

Strengths: Tests generalisation to new entities.

Watch out: Requires a reliable group key; uneven folds.

Temporal split or rolling origin
Best for: Forecasting and any model deployed forward in time

Strengths: Matches production; prevents time travel.

Watch out: Fewer data for training; non-stationarity affects scores.

Interview signals & numbers to know

When this topic comes up

  • “AUC is 0.99”
  • “Works offline but not in production”
  • Target leakage
  • GroupKFold
  • Nested cross-validation

Benchmarks & rules of thumb

99.84% -
test rows with a training sibling under a random 5-record split
±1.9 pts -
95% interval for 90% accuracy on 1,000 rows
70/15/15 -
common train, validation, test proportions

Common mistakes & follow-ups

Common interview mistakes

  • Using a feature that is updated after the outcome.
  • Applying SMOTE or target encoding before the split.
  • Selecting features on the full dataset, then cross-validating.

Likely interviewer follow-ups

  • What is data leakage and how do you detect it?
  • How would you split time-series or grouped data?
  • Why use a Pipeline in cross-validation?
Interview tip: Describe a concrete leak you'd look for (a post-outcome feature) and the one-line fix (a Pipeline). Specifics prove experience.

Knowledge check

Loading quiz

Put it into practice

Practice related interview Q&A

Apply Train-Validation-Test Splits & Data Leakage with data science interview Q&A and hands-on practice.

Open Data Science Q&A →Machine Learning Q&A
Previous topic
Supervised vs Unsupervised Learning
Next topic
Bias-Variance Tradeoff