Data Splitting, Cross-Validation & Defeating Data Leakage
Part I · Chapter 2: Train/Val/Test vaults, Stratified & Group K-Fold, Time-Series splits, and catching silent Data Leakage before launch
Data Leakage is the #1 reason models score 98% in notebooks and crash to 60% on Day 1 in production!
Wrapping every scaler, imputer, and encoder inside a scikit-learn `Pipeline` guarantees zero preprocessing leakage across every CV fold and production serving call.
Using random splits on time-series or repeated-user datasets leaks future/user identity into validation — costing companies millions in bad launch decisions.
'Walk me through 3 different types of Data Leakage and how you prevent each one' is one of the highest-signal Senior DS/ML interview questions!
You are building a stock-price / sales forecasting model using 3 years of daily data. You randomly shuffle all rows and do a 5-Fold Cross-Validation. What happens?
- Separate Train (learn weights), Validation (tune hyperparameters), and Test (final locked exam) so you never overfit the test set.
- Choose the right split strategy: Stratified K-Fold (imbalanced classes), GroupKFold (repeated users/patients), and Walk-Forward (time series).
- Spot and eliminate both Target Leakage (future info in X) and Preprocessing Leakage (fitting scalers/imputers before splitting!).
- Implement deterministic Stratified Train/Test and K-Fold splitters from scratch.
The entire goal of Machine Learning is generalization — performing well on brand-new unseen data, not memorizing yesterday's spreadsheet. Imagine a student who memorizes the exact practice test answers: they score 100% in class and fail the real exam! Clean Data Splitting & Cross-Validation is how we simulate the real future honestly.
1. The 3-Way Split Vault & K-Fold Cross-Validation
Why can't you just split data into Train (80%) and Test (20%), try 50 different models on the Test set, and report the best Test score? Because you just used the Test set to make decisions — by pure luck, the 50th model will overfit the quirks of that 20% slice! Keep a 3rd Validation set (or rotate K-Fold CV inside Train) for tuning, and lock the Test Set in a vault until the very end!
How K-Fold Cross-Validation Works
- Lock away 15%–20% as your untouched Final Test Set.
- Split the remaining 80% into equal folds (typically or ).
- For each fold : train on the other folds, evaluate on fold .
- Average the validation scores (and inspect their standard deviation!) to compare models reliably.
You have 1,000 rows: 950 Legit (0) and 50 Fraud (1). In 5-Fold Stratified Cross-Validation, how many total rows and how many Fraud rows are inside EACH validation fold?
2. Defeating Data Leakage (The Silent Career-Killer!)
A team built a hospital pneumonia AI that scored 99% AUC in offline validation. On launch day it collapsed! Why? One feature column was antibiotic_prescribed — doctors only prescribe that antibiotic after diagnosing pneumonia! That's Target Leakage (a clue from the future). Even subtler is Preprocessing Leakage: fitting StandardScaler or TargetEncoder on ALL rows before splitting lets test-set averages whisper into training!
The Two Golden Anti-Leakage Rules
- Split FIRST, transform SECOND: Fit every imputer, scaler, encoder, and feature selector strictly on
X_train(.fit_transform(X_train)), then apply.transform(X_val)ONLY! - Time-Travel Audit on Every Feature: Ask "Would this exact column value ALREADY exist in our database 1 millisecond BEFORE we need to make a prediction?" If not, delete it immediately!
Toggle Leaky vs. Clean pipelines in the Sabotage Lab below to see the exact gap!
Switch between a Leaky Pipeline (target-encoding & scaling on ALL rows before splitting) and a Clean Pipeline (fit ONLY on Train Fold):
Pause & Check: You want to impute missing incomes with the column median and run 5-Fold CV. Where MUST the median be computed?
3. Choosing the Right Split: Stratified vs. Group vs. Walk-Forward
Not all datasets are independent rows! If you're diagnosing X-rays where each patient took 5 scans, putting 3 scans of Patient #42 in Train and 2 scans in Test lets a neural net cheat by recognizing Patient #42's ribs instead of the tumor! Use GroupKFold by patient_id!
The 3-Second Split Selector
- Imbalanced Classification (fraud, clicks, rare disease): → Stratified K-Fold (identical class ratios per fold).
- Multiple rows per user / patient / store: → GroupKFold (same entity NEVER in both train and val!).
- Time-ordered data (demand, stocks, churn over months): → Walk-Forward / Expanding Window Split (ALWAYS train on past, validate on future!).
You are building a recommendation model using 12 months of user click logs (Jan–Dec) where each user appears ~40 times. Should you use random 5-Fold CV? If not, what split should you use?
The exact honest questions almost every beginner wonders — answered in plain English without hiding behind jargon.
Once 5-Fold CV tells you the winning recipe (say, Ridge(alpha=3.0)), you retrain ONE final Ridge(alpha=3.0) model on 100% of the Train+Val pool (more data = better model!), evaluate it ONCE on the locked Test Vault to confirm performance, and ship!
Compare Stratified K-Fold vs. Walk-Forward Time-Series Splitting
Fraud & Credit Risk Modeling
Uses Time-Based Out-of-Time (OOT) validation splits so models are tested against newer fraud tactics, not past leaks.
Medical Imaging Diagnostics
Strictly enforces Patient-Level GroupKFold so scans from the same patient or hospital scanner never cross train/test boundaries.
Kaggle & Automated ML (AutoML)
Out-of-Fold (OOF) predictions from Stratified K-Fold power stacking ensembles without overfitting.
A/B Feature Selection Pipelines
scikit-learn Pipelines ensure exact train/serve parity between offline CV and real-time production APIs.
from sklearn.impute import SimpleImputer
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import StratifiedKFold, cross_val_score
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import StandardScaler
import numpy as np
rng = np.random.default_rng(0)
X = rng.normal(size=(500, 6))
y = (X[:, 0] + rng.normal(scale=1.2, size=500) > 1.2).astype(int) # ~15% positive
# ZERO LEAKAGE: Imputer + Scaler fit strictly inside EVERY train fold!
pipe = Pipeline([
("imputer", SimpleImputer(strategy="median")),
("scaler", StandardScaler()),
("clf", LogisticRegression()),
])
cv = StratifiedKFold(n_splits=5, shuffle=True, random_state=42)
scores = cross_val_score(pipe, X, y, cv=cv, scoring="roc_auc")
print(f"5-Fold Stratified AUC: {scores.mean():.3f} ± {scores.std():.3f}")