Unit 7 · ML & applied AI · Lesson 2 of 13
Data splits, leakage and data quality
Step 1: Learn the ideas
- Training, validation and test roles; test-set reuse
- Stratified, group and time-based splits
- Cross-validation and nested cross-validation
- Preprocessing pipelines fit on training folds only
- Target leakage and label proxies
- Temporal leakage and point-in-time feature joins
- Duplicate and near-duplicate leakage, including benchmark contamination
- Data quality: label noise, missingness, schema and distribution checks
Why it matters
Many impressive offline results fail in production because the evaluation did not resemble deployment. A split that lets the model see the same user, the same document or the future during training measures memorization, not generalization. Interviewers probe this with "offline AUC is excellent but production is poor: what happened?" and with design questions where choosing the right split is most of the answer.
Core ideas
Three roles. Training data fits parameters. Validation data, or cross-validation, chooses hyperparameters, features, thresholds and stopping points. The test set estimates final performance, once. Every decision made by looking at a set leaks information about it, so a test set that has guided many choices quietly becomes a second validation set with an optimistic score. Keep a held-out set you consult rarely, and refresh it once it has been used up.
Split by the unit of deployment. Ask what the model will face: new rows, new users, new documents or next month's data.
- Random, stratified splits fit only when examples are independent and the future resembles the past; stratify on the label when classes are rare.
- Group splits keep every example from one entity (patient, user, session, document, company) on one side. Otherwise the model can score well by recognizing the entity: a user's habits, a document's boilerplate, one company's writing style.
- Time-based splits train on the past and evaluate on a later window, with several forward-chaining folds if needed. Leave a gap when labels mature slowly, such as churn defined over the following 30 days.
Leakage types.
- Preprocessing leakage: fitting a scaler, imputer, vocabulary, PCA, feature selector or target encoder on the full dataset before splitting, so its statistics include test information. Fit every transformation inside a pipeline, on training folds only. Feature selection and target encoding leak far more than scaling.
- Target leakage: features that are consequences or proxies of the label, such as "refund issued" when predicting fraud, or a status field updated after the outcome. For each feature ask whether it exists at prediction time, with the value it would have then.
- Temporal leakage: aggregates over windows that extend past the prediction time, or joins against current tables instead of point-in-time snapshots.
- Duplicate and near-duplicate leakage: the same image, reposted text, augmented copies or templated documents in both splits. For LLMs, benchmark items present in pretraining data (contamination) are the same problem at web scale.
Cross-validation. K-fold CV reduces the variance of the estimate on small data, but every fold must respect grouping and time order. If you tune hyperparameters with CV and report that same CV score, it is optimistic; nested CV (an inner loop for selection, an outer loop for estimation) measures the performance of the whole selection procedure.
Data quality is part of evaluation. Before modeling, check label agreement on a sample, missingness patterns (missingness can itself encode the label), duplicates, class balance per split, value ranges and schema. A model trained on silently broken data can still produce a smooth loss curve.
Common misconceptions
- "Scaling before splitting is harmless because it is unsupervised." It still uses test statistics; the effect is usually small for scaling but large for feature selection or target encoding. Fit every transformation on training data only.
- "Shuffled k-fold is always the safe default." For time series or grouped data it overstates performance; use group-aware or forward-chaining splits.
- "Stratification prevents leakage." It only balances label proportions; it does nothing about shared entities or time.
- "A very predictive feature is a very useful feature." Suspiciously strong features are often label proxies unavailable at prediction time; check their timing and provenance.
- "The test set is safe as long as I never train on it." Repeatedly choosing models by test score is fitting to it.
- "Deduplication means removing exact matches." Near-duplicates (re-encoded images, lightly edited text, templated pages) leak just as well; find them with hashing or embedding similarity.
How to approach it
Begin every design answer with "what will the model see at prediction time, and about which entities?" and derive the split from that. Build a deliberately leaky pipeline, measure the inflation, then fix it. When reviewing someone's work, run through a leakage taxonomy as a checklist. Senior-level discussions add how labels are generated, how features are joined point-in-time, and how to detect leakage after launch (a large offline-online gap, or one feature dominating importance).
Suggested order
- 1Read the scikit-learn "Common pitfalls and recommended practices" page on inconsistent preprocessing and data leakage, and run its examples.
- 2Read the scikit-learn cross-validation guide, focusing on the iterators for grouped data (GroupKFold and related) and for time series (TimeSeriesSplit), and on using them with pipelines.
- 3Skim the Google Machine Learning Crash Course pages "Dividing the original dataset" and "Data characteristics" as a quick baseline.
- 4Read the leakage taxonomy in Kapoor and Narayanan and turn it into your own review checklist.
- 5Read the Rules of ML "Training-Serving Skew" section (Rules #29 to #37), especially Rule #33 on testing with data from after the training period.
- 6Run the three leakage experiments in the practice guidance and write one paragraph per experiment on what leaked.
Step 2: Check off what you can do
Tap each one you can genuinely do or explain. Each earns 10 XP.
Step 3: Go deeper
scikit-learn: Common pitfalls and recommended practicesStart here
scikit-learn documentationConcrete examples of preprocessing leakage and inconsistent preprocessing, with the pipeline-based fix.
Open(opens in a new tab)Link responded, 5 Oct 2026scikit-learn User GuideStart here
scikit-learn documentationSection: Cross-validation: evaluating estimator performance
Cross-validation iterators for grouped and time-ordered data and how to combine them with pipelines.
Open(opens in a new tab)Link responded, 5 Oct 2026Leakage and the Reproducibility Crisis in ML-based Science
arXivA taxonomy of leakage types drawn from real published failures; use it as a review checklist.
Open(opens in a new tab)Link responded, 5 Oct 2026Machine Learning Crash Course
Google for DevelopersSection: Datasets: Dividing the original dataset
Quick refresher on training, validation and test roles and on duplicates across splits.
Open(opens in a new tab)Link responded, 5 Oct 2026Rules of Machine Learning: Best Practices for ML Engineering
Google for DevelopersSection: Training-Serving Skew (Rules #29 to #37)
Practitioner rules on point-in-time data, changing joined tables and testing on data from after the training period.
Open(opens in a new tab)Link responded, 5 Oct 2026
Step 4: Practice
Run three small experiments in a notebook. (1) Preprocessing leakage: generate a dataset with a few hundred rows, thousands of pure-noise features and a random label; select the top features by correlation with the label on the full data, then cross-validate a classifier, and repeat with selection inside a Pipeline per fold. The first score is well above chance, the second is not. Also compare fitting a StandardScaler before versus after the split and note how small that effect is. (2) Group leakage: build data with many rows per user and a user-specific signal; compare KFold with GroupKFold and explain the gap. (3) Temporal leakage: compute a rolling-window feature with and without future rows and compare forward-chaining evaluation results.
No external problems are linked; follow the guidance above.
Record attempts on each problem’s page (+15 XP, +10 more when solved on your own).
Step 5: Test yourself
Answer each one out loud or on paper before you finish the lesson.
- Question 1A churn model scores much higher offline than online. Name three leakage hypotheses and how you would test each.
- Question 2Why does a group split matter for medical images with several scans per patient?
- Question 3Which preprocessing steps leak the most when fit on all data, and why?
- Question 4How would you build features for a model that predicts at time t from tables that are updated continuously?
- Question 5How do near-duplicates end up in both splits, and how would you find them?
- Question 6When does reusing a test set turn it into a validation set?
You’re done when you can
- Given three deployment scenarios, choose and justify a split for each in under five minutes.
- Demonstrate preprocessing leakage and its pipeline fix in code, and explain why the size of the effect depends on the transformation.
- List at least five leakage sources and a detection method for each without notes.
- Explain nested cross-validation and when its extra cost is justified.
Finish the lesson
Unlocks next: Metrics, calibration, thresholds and uncertainty


