Train-Validation-Test Splits & Data Leakage
Split data honestly and prevent leakage from preprocessing, targets, and time.
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
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.
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.
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.
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.
How it works, step by step
Step 1 of 41. Define the prediction moment
Write when the model will predict and which data is available at that time.
- 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
Strengths: Simple; preserves class balance.
Watch out: Leaks when rows are related or time-ordered.
Strengths: Tests generalisation to new entities.
Watch out: Requires a reliable group key; uneven folds.
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?
Knowledge check
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.