Chapter 2 of 4 · ~25 min read & lab+65 XP
Chapter 2 · Machine Learning

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

Why ML Engineers & Data Scientists Actually Need This

Data Leakage is the #1 reason models score 98% in notebooks and crash to 60% on Day 1 in production!

ML / AI Engineer

Wrapping every scaler, imputer, and encoder inside a scikit-learn `Pipeline` guarantees zero preprocessing leakage across every CV fold and production serving call.

Data Scientist

Using random splits on time-series or repeated-user datasets leaks future/user identity into validation — costing companies millions in bad launch decisions.

Interview & Debug Edge

'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!

Step 0 · Test Your Gut Before Any Math!

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?

What You Will Master in This Chapter
  • 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.
Plain-English Symbol Decoder · Click Any Symbol Before We Begin
No mysterious math notation — translate everything into English first
How to Say It Aloud
“Three-Way Data Split”
Plain-English Meaning
Train = textbook practice; Validation = mock exams to pick settings; Test = locked final exam touched ONCE!
Everyday Example
60% Train / 20% Validation / 20% Locked Test Vault.
Story-First Intuition, Visual Diagrams & Interactive Walkthroughs

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

Everyday Story First (Zero Math Yet!)

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!

80% Train (5-Fold Cross-Validation) + 20% Locked Final Test VaultTraining & Validation Pool (80%)LOCKED TEST(20% · Touch ONCE!)Green = Train Folds · Amber = Rotating Validation Fold (Average all 5 scores!)
Figure 2.1 — Holdout + K-Fold Cross-Validation: lock the Test Set in a vault until the very end; rotate K validation folds inside Training to tune hyperparameters reliably.

How K-Fold Cross-Validation Works

  1. Lock away 15%–20% as your untouched Final Test Set.
  2. Split the remaining 80% into KK equal folds (typically K=5K = 5 or 1010).
  3. For each fold i=1,…,Ki = 1, \dots, K: train on the other K−1K - 1 folds, evaluate on fold ii.
  4. Average the KK validation scores (and inspect their standard deviation!) to compare models reliably.
Try It YourselfWarm-Up

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!)

Everyday Story First (Zero Math Yet!)

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!

❌ LEAKY PIPELINE (Fake High Score!)1. scaler.fit_transform(ALL_DATA) ← LEAK!↓2. train_test_split(...) (Test μ,σ already leaked!)Val looks great; production crashes!✓ CLEAN PIPELINE (Zero Leakage!)1. Split FIRST → X_train | X_test↓2. fit(X_train) → transform(X_test) ONLY!Honest estimate of unseen production data!
Figure 2.2 — Preprocessing Data Leakage: fitting a scaler or imputer on the full dataset leaks test-set statistics into training — ALWAYS fit strictly inside each train fold!

The Two Golden Anti-Leakage Rules

  1. 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!
  2. 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!

Hands-On Mini-Lab · Watch Data Leakage Fake a 94% Score While Production Crashes!

Switch between a Leaky Pipeline (target-encoding & scaling on ALL rows before splitting) and a Clean Pipeline (fit ONLY on Train Fold):

Offline Validation AUC
0.942 (FAKE!)
Validation rows peeked at their own target/mean!
Real Production AUC (Unseen Future)
0.710 (CRASH!)
−23% drop on launch day because future stats don't exist!
Pause & Check · Quick Intuition Pulse

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

Everyday Story First (Zero Math Yet!)

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!

Walk-Forward Time-Series Validation (NEVER Shuffle Future Into Past!)Split 1Past TrainFuture ValSplit 2Past TrainFuture ValSplit 3Past TrainFuture Val
Figure 2.3 — Choosing the Right Split Strategy: use Stratified for imbalanced classes, GroupKFold when users/patients repeat, and Walk-Forward Splits for time series!

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!).
Try It YourselfStandard

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?

“Wait, I'm Confused...” · Teacher Office Hours Q&A

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!

Interactive Visual Lab
Lab Challenge: Inspect BOTH Stratified K-Fold and Walk-Forward Time-Series modes in the Cross-Validation Deep Lab below!
Interactive Deep Lab · Cross-Validation & Time-Series Split Explorer

Compare Stratified K-Fold vs. Walk-Forward Time-Series Splitting

Goal: Inspect both Stratified K-Fold & Time-Series modes
Intuition Takeaway: Split FIRST, transform SECOND (always inside a Pipeline); match your split to your data structure (Stratified for imbalance, Group for repeated entities, Walk-Forward for time); and lock the Test Set until the end!
Where This Powers Real ML, Deep Learning & GenAI

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.

Production NumPy & PyTorch Code Patterns
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}")
Common ML Interview Traps & Numerical Pitfalls
Trap #1: Applying SMOTE oversampling to the entire dataset BEFORE train_test_split.
Best Practice: Oversampling before splitting puts near-identical synthetic copies of test rows into Train → massive fake 99% recall! ALWAYS oversample strictly inside the Train fold!
Trap #2: Tuning hyperparameters 100 times on the Test Set and reporting that Test score as unbiased.
Best Practice: Once you use a split to pick hyperparameters, it's a Validation set — NEVER touch the Final Test Vault until model selection is 100% frozen!
Trap #3: Using random K-Fold on time-series forecasting.
Best Practice: Always use `TimeSeriesSplit` / Walk-Forward splits so Train timestamps strictly precede Validation timestamps!
Chapter Mastery Check (+65 XP)
Score: 0 / 5
11. 10,000 X-rays come from 2,000 patients (5 per patient). Best CV splitter to prevent leakage?
22. Fitting StandardScaler on ALL rows before calling train_test_split causes:
33. Why do we use StratifiedKFold on a 1%-fraud dataset?
44. Which split is mandatory for forecasting next month's retail demand?
55. What happens if you run SMOTE oversampling BEFORE splitting Train and Test?

Apply What You Learned — Solve Matching Coding Problems