This lesson on Data Leakage — The #1 ML Bug is hands-on and example-driven. You will be able to identify and prevent various types of data leakage that cause machine learning models to overestimate their performance. You will learn the critical best practice: always split your data into train/test sets before applying any feature preprocessing or transformation.
What You'll Be Able To Do
- Define data leakage and its impact on model utility.
- Identify premature featurization as a primary source of leakage.
- Apply the correct sequence of steps for data splitting and transformation.
- Recognize specific types of leakage, including group and time leakage.
- Explain why cross-validation requires feature processing within each fold.
Topics Covered in Data Leakage — The #1 ML Bug
- ML Objective (0:00 - 0:30) — The goal of machine learning is training a model to predict accurately on unseen data.
- Defining Leakage (0:30 - 1:00) — Data leakage occurs if the model trains on information that will not be available during production prediction.
- TF-IDF Example (1:00 - 2:30) — Computing TF-IDF on the entire corpus before splitting the data causes leakage.
- Standardization Example (2:30 - 3:50) — Calculating mean and standard deviation on the full dataset before splitting is a common leakage error.
- The Solution (3:50 - 4:30) — To avoid leakage, always split the data first, then apply transforms only on the training set.
- Cross-Validation (4:30 - 5:30) — Feature processing must be done within each fold of cross-validation after the validation data is split.
- Duplicate Rows (5:30 - 6:00) — Duplicate rows between train and test sets, often from oversampling, can cause training example leakage.
- Group Leakage (6:00 - 7:00) — Group leakage happens when related data points, like multiple X-rays from one patient, are split across train and test sets.
- Time Leakage (7:00 - 8:00) — In time series data, mixing future data into the training set creates time leakage.
- Summary & Impact (8:00 - 8:40) — Leakage causes the model to overestimate its utility, leading to failure when deployed in a production environment.
SQL Cheat Sheet
-
Data Leakage— Training model uses information unavailable during production prediction -
Premature Featurization— Applying transforms before splitting data into train and test setsSELECT TFIDF(corpus) FROM documents; -
Standardization— Normalizing features using mean and standard deviationSELECT (X - AVG(X)) / STDDEV(X) FROM features; -
Train-Test Split— Separating data into sets for model development and evaluationSELECT * FROM data WHERE split = 'train'; -
Group Leakage— Data from the same group appears in both training and test splitsSELECT * FROM xrays WHERE patient_id = 123; -
Time Leakage— Future data is included in the training set for time seriesSELECT * FROM stock_data WHERE date < '2023-01-01';
Comparison Table
| Process Step | Correct (Avoids Leakage) | Incorrect (Causes Leakage) |
|---|---|---|
| Order of Operations | Split first, then transform. | Transform first, then split. |
| Statistic Calculation | Calculate mean/std dev only on Train. | Calculate mean/std dev on entire data. |
| Resulting Model Utility | Accurate estimate of performance. | Overestimated utility; fails in production. |
Common Pitfalls
- Mistake: Computing standardization statistics (mean/std dev) on the entire dataset. Avoid: Calculate statistics only on the training set, then apply them to the test set.
- Mistake: Calculating TF-IDF across the entire document corpus before splitting. Avoid: Compute TF-IDF only on the training documents after the split is complete.
- Mistake: Allowing duplicate rows between the training and validation sets. Avoid: Ensure data augmentation or upsampling is done carefully to prevent cross-split duplicates.
- Mistake: Using random splitting on non-IID data like patient X-rays. Avoid: Ensure all data points belonging to a single group stay within one split (train or test).
FAQs
- Why does data leakage cause models to fail in production? Leakage causes the model to partially memorize test data features, leading to unrealistically high performance scores during evaluation. In production, this memorized information is absent, causing performance to drop significantly.
- How should I handle feature processing during cross-validation? For every fold, the feature processing (like standardization) must be calculated only on the training data for that fold, and then applied to the validation data.
- What is the primary rule for avoiding data leakage? Always split the data into training and testing sets first, and only then perform any feature preprocessing or transformation steps.
- What is 'time leakage'? Time leakage occurs in time series data when future information is accidentally included in the training set, making prediction unrealistically easy.
🛡️ Leakage-Prevention Checklist (Temporal + Group-Aware Splits)
Leakage is the #1 reason offline metrics lie. Harden every evaluation:
- Split first, preprocess later. Fit imputers, scalers, encoders, and
target statistics on the TRAIN fold only — never on the full frame. In
sklearn, enforce this structurally with
Pipeline+ColumnTransformer. - Respect time. For temporal data use time-based splits (train on past, validate on future). Random k-fold on timestamped rows leaks the future.
- Respect groups. When rows share an entity (user, account, device), use
GroupKFold/StratifiedGroupKFoldso no entity spans train and valid. - Audit features. Any feature computed with knowledge of the label or the future (e.g. "days until churn", aggregates over the full window) is suspect — drop it or recompute point-in-time.