What is data leakage and how do you prevent it?
Written by the mlprep team · Updated
What is data leakage in ML? Give me examples of how it appears, and how you'd catch and prevent it.
What leakage is#
Data leakage occurs when information unavailable at prediction time — or information that encodes the target — is used during training. The model learns patterns that won't exist in production, so training/validation metrics overestimate real-world performance.
Leakage is often silent: the model trains fine, metrics look great, it fails in production.
Type 1: Target leakage (feature leaks the label)#
A feature is computed using information that's only available after the target is known.
Example: Predicting hospital readmission. Feature: "number of follow-up appointments scheduled." But patients who are readmitted often have appointments scheduled because they were readmitted — the feature encodes the outcome.
Example: Predicting loan default. Feature: "account status = 'in collections'" — this is true because they defaulted, not a predictor of default.
Detection: a single feature with very high importance or a model with suspiciously high accuracy. A feature strongly correlated with the target that shouldn't logically be causal at prediction time.
Prevention: for each feature, ask "does this information exist at the moment I make the prediction?" Apply a strict temporal cutoff.
Type 2: Train-test contamination#
Information from the test set flows into training, making the model implicitly "see" the test data.
Scaling on the full dataset: fitting a scaler or imputer on all data before splitting means the training scaler has seen test distribution statistics. Fix: fit scaler on train only, transform test.
Target encoding on full data: encoding using full-dataset mean targets means training rows see test labels. Fix: use out-of-fold encoding.
Cross-validation with preprocessing outside CV: applying PCA on all data, then doing CV. Fix: put all preprocessing inside the cross-validation loop via sklearn Pipelines.
Type 3: Temporal leakage#
In time-series or any temporal data, using future information to predict past events.
Example: predicting user churn. Features include "was active in the 30 days after prediction date" — that's the future.
Example: predicting stock price. Training includes data from 2023 for predicting 2020 prices in CV — the model effectively sees the future.
Fix: strict temporal train/val splits. For CV: walk-forward validation (train on [t0, t1], validate on [t1, t2], train on [t0, t2], validate on [t2, t3]). Never shuffle time-series data before splitting.
Type 4: Group leakage#
The same entity (user, patient, product) appears in both train and test. A model memorizes entity-specific patterns rather than generalizing.
Example: predicting user behavior. Same user in train and test — model learns that user's historical behavior and memorizes it, not a generalizable pattern.
Fix: group-aware splits. Split by user ID / patient ID, never by row. In CV, use GroupKFold.
How to catch leakage#
- Performance too good? Investigate.
- Feature importance dominated by one "surprising" feature? Investigate.
- Model performs well on validation but degrades immediately in production? Suspect leakage.
- Audit features with domain knowledge: could this data exist before the prediction timestamp?
- Check time ordering: validate that feature timestamps precede the target timestamp row by row.
Senior/staff considerations#
At senior/staff level, leakage prevention is a system property. It is not enough to remember "split before scaling." You need data contracts and evaluation design that preserve the prediction-time information boundary.
A strong production checklist:
- Define the prediction timestamp, label window, feature lookback window, and data availability delay for every feature.
- Store event time separately from processing time; late-arriving data can create leakage even when event timestamps look correct.
- Build point-in-time feature joins so training examples only see feature values available at that historical decision time.
- Split by the unit of generalization: time for forecasting, user/patient/account for entity generalization, geography/product for launch generalization when relevant.
- Put preprocessing, target encoding, feature selection, imputation, and dimensionality reduction inside the CV fold.
- Add leakage tests: impossible-feature audits, feature timestamp assertions, train/serve feature parity checks, and suspicious-performance alerts.
The staff-level answer also recognizes that leakage can be intentional in offline analysis. For example, using future labels to build a retrospective cohort may be fine for analysis but invalid for model training. The key is whether the information exists at prediction time.
Interview red flags#
- Fitting scalers, imputers, or encoders on the full dataset before the train/test split.
- Randomly splitting time-series or user-grouped data, so the model sees the future or the same entity in both splits.
- Accepting suspiciously high validation accuracy without auditing the top features.
- Not checking whether each feature would really be available at prediction time.
The key takeaway unlocks after you reveal an expert answer.
Key Takeaway
Four leakage types: (1) target leakage — feature contains the label (apply temporal/causal audit), (2) train-test contamination — fit preprocessing on train only, use Pipelines, (3) temporal leakage — no shuffling of time-series, use walk-forward CV, (4) group leakage — split by entity ID not rows. Red flags: suspiciously high accuracy, single dominant feature, immediate production degradation. Leakage produces models that look great in training and fail in deployment.
Follow-up Questions to Test Yourself
Interviewers often pivot here once you cover the core concept.
- How would you structure a sklearn Pipeline to guarantee no leakage during cross-validation?
- Your colleague ran CV and got 0.98 AUC on what should be a hard problem. What's your checklist for diagnosing leakage?
- In a recommender system, how do you prevent leakage when evaluating offline metrics?
How confident do you feel explaining this?
Track your understanding or flag it to revisit before your next loop.
Related Questions
Which features are safe to use when predicting future events — temporal leakage in practice
What is train-serve skew and how do you prevent it?
How do you handle the cold start problem in recommendation systems?
How would you design a feature store for a large ML platform?