Lesson 8 of 10
Data Leakage Prevention & Robust Train-Validation-Test Splits
Data Leakage is the subtle, catastrophic contamination of the training process with information that will not legitimately be accessible at inference time. It produces stellar cross-validation scores that collapse instantly in production. Leakage occurs in three primary forms: Preprocessing Leakage (scaling/imputing before splitting), Target Leakage (including features that causally result from the target), and Temporal Leakage (shuffling future observations into past training sets).
Detecting & Fixing Data Leakage in Code
import numpy as np
import pandas as pd
from sklearn.model_selection import train_test_split, TimeSeriesSplit
from sklearn.preprocessing import StandardScaler
from sklearn.linear_model import Ridge
from sklearn.metrics import mean_squared_error
# Synthetic financial dataset with temporal ordering
np.random.seed(42)
dates = pd.date_range(start="2026-01-01", periods=1000, freq='D')
trend = np.linspace(10, 100, 1000)
noise = np.random.normal(0, 5, 1000)
prices = trend + noise
df = pd.DataFrame({'date': dates, 'price': prices})
df['lag_1'] = df['price'].shift(1)
df['lag_7'] = df['price'].shift(7)
# TARGET LEAKAGE EXAMPLE: 'next_day_high' is determined in the future!
df['future_leak'] = df['price'].shift(-1) # Causal leak!
df.dropna(inplace=True)
# 1. THE CATASTROPHIC WAY: Random Shuffle Split on Time-Series Data
X_leak = df[['lag_1', 'lag_7', 'future_leak']]
y = df['price']
X_tr_bad, X_te_bad, y_tr_bad, y_te_bad = train_test_split(X_leak, y, test_size=0.2, shuffle=True)
model_bad = Ridge().fit(X_tr_bad, y_tr_bad)
print(f"Artificial 'Leaked' Test MSE: {mean_squared_error(y_te_bad, model_bad.predict(X_te_bad)):.4f} (Deceptively perfect!)")
# 2. THE PRODUCTION-ROBUST WAY: Temporal Split Without Target Leak
X_clean = df[['lag_1', 'lag_7']] # Strictly historical features
split_idx = int(len(df) * 0.8)
X_train_real, X_test_real = X_clean.iloc[:split_idx], X_clean.iloc[split_idx:]
y_train_real, y_test_real = y.iloc[:split_idx], y.iloc[split_idx:]
# Fit scaler ONLY on historical train split
scaler = StandardScaler()
X_tr_scaled = scaler.fit_transform(X_train_real)
X_te_scaled = scaler.transform(X_test_real) # Transform ONLY
model_real = Ridge().fit(X_tr_scaled, y_train_real)
print(f"Realistic Production Test MSE : {mean_squared_error(y_test_real, model_real.predict(X_te_scaled)):.4f}")Pro Tip: The Feature Timestamp Audit Rule
For every single feature column x in your training set, ask: 'Was value x recorded strictly BEFORE the event timestamp t_event?' If a feature contains information recorded at or after the prediction moment (e.g., `refund_initiated_at` when predicting customer churn), it is target leakage and must be purged immediately.
MlTrainTestSplitLeakage Visual Representation
Hands-On Challenge: Leakage Audit Checklist
Audit an e-commerce dataset for leakage: Identify whether features like `total_support_tickets_filed_in_2026`, `account_closed_reason`, or `last_payment_status` introduce target leakage when training a model to predict user subscription renewal at the 30-day mark.
Quick Quiz & Key Concept Checks
Common Pitfall: Imputing Missing Values Before Train-Test Split
Imputing missing values using the global median or mean of the whole dataset leaks test distribution statistics into the training fold. Always perform imputation inside a `Pipeline` or fit your imputer strictly on the training partition.
Finished this lesson?