7 routes42 sections324 units

Unit 1.4 · about 4 h

131 / 324

Leakage: target, future, entity, duplicate, preprocessing and feedback

Leakage is the usual cause of scores that are too good to deploy. Each kind has a different audit, so taxonomy first, then tests.

  • explain
  • measure

You can now

  • Explain target leakage, future leakage, entity overlap, duplicate contamination, preprocessing leakage, label delay, and feedback leakage.
  • Diagnose an unexpectedly high score by auditing duplicate entities, time, preprocessing, label construction, selection, and metric code.
  • Quantify the effect of repairing one leakage defect while keeping the model and evaluation fixed.

Covers

  • Target, future, entity, duplicate and preprocessing leakage
  • Label delay, selection bias and feedback leakage

Study, in this order

4 steps

  1. Leakage definition, repairs, and the `SelectKBest` demo
    scikit-learn - Common pitfalls and pipelines

    12.2 Data leakage with the never-call-fit-on-test rule; 12.2.1 How to avoid data leakage (split first, fit on train, transform both); 12.2.2 Data leakage during pre-processing with the SelectKBest wrong run at 0.76 versus the right run at 0.50 on random labels and the pipeline cross-validation at 0.43 +/- 0.05

  2. Target construction in the Bike dictionary
    UCI Bike Sharing Dataset

    Additional Variable Information: casual, registered, and cnt definitions, with cnt the count of total rentals including both casual and registered

    Depth · Read the definitions, then verify the identity on the file yourself: casual plus registered equals cnt on every hour.csv row (verified max difference 0 on 17379 rows).

  3. Freshness, export checks, and monitoring
    Rules of Machine Learning - first controls

    Rule 8: Know the freshness requirements of your system; Rule 9: Detect problems before exporting models, including the held-out AUC sanity check

  4. Sampling discipline and production monitoring
    Hands-On Machine Learning with Scikit-Learn and PyTorch - Chapters 1 and 2

    Get the data, item 11 (test set aside, no snooping); Launch: monitoring code, slow degradation and rot, input-quality checks, retraining on fresh data, and the human pipeline for labels

Focus on

  • Leakage is any use of information unavailable at prediction time (section 12.2). The repair never varies: split first, fit on train only, transform both, preferably inside a Pipeline.
  • The SelectKBest demo quantifies it. Selecting on all of \(200 \times 10000\) random features then splitting scores 0.76 against chance near 0.50; selecting on train only scores 0.50 with pipeline cross-validation at 0.43 +/- 0.05. Distance above chance on random labels is the alarm.
  • Bike cnt is defined as casual plus registered on every row, so both are target parts, never features. A linear model on the two scores RMSE 0.0 with coefficients [1, 1] and intercept 0; the label-free 12-feature linear baseline on the same chronological split scores 192.3.
  • Delay, selection, and feedback are leakage over time and policy: late labels need freshness limits and a human labeling pipeline, selected training rows need the sampling discipline of unit 3, and predictions that reshape future labels need input monitoring and pre-export checks. Production feedback control stays excluded per leaveForLater.

Reproduce closed-book

Closed-book, re-run the SelectKBest pair (wrong 0.76, right 0.50 on random labels) and the bike identity check (casual plus registered equals cnt on all 17379 rows, leaking linear model RMSE 0.0 with coefficients [1, 1]). State both repairs: fit selectors and scalers on train only inside a Pipeline, and drop casual and registered from cnt features.

Traps

  • Judging leakage by metric movement alone. Fitting the bike weather scaler on all rows versus train only gives RMSE 200.95 both ways with LinearRegression, because least-squares predictions are unchanged by any per-column rescaling; even Ridge and 10-nearest-neighbors move by under 0.05. The procedure is still broken. Test the procedure, not just the score.
  • Calling deduplication a leakage fix by itself. Removing exact duplicates without fixing split ownership still lets entity twins straddle train and test; assert group and entity disjointness after dedup, per unit 3.
  • Treating feedback as a modeling bug. When serving decisions select tomorrow labels, no refit breaks the loop; the contract must log exposure and keep an unaffected holdout slice, which the mini-project records as a monitoring exclusion.

Practice

The section mini-project covers this: seeded global-scaling, target-derived-feature, and partition-duplicate defects, each caught by a failing test with the conclusion change reported after repair.

Self-test

  1. SelectKBest on all \(200 \times 10000\) random features then split scores 0.76. Why is that proof of leakage rather than signal?

  2. Predicting bike cnt from casual and registered gives RMSE 0.0. Good model?

  3. Scaling bike weather on all rows versus train only leaves a LinearRegression RMSE at 200.95 both ways. Leak or not?

  4. Labels arrive two weeks late and serving prioritizes flagged users. Name the two risks and one guard each.

  5. Copying 500 test rows into bike train moves a weather-only decision tree from RMSE 219.4 to 214.1. Small move, so harmless?

Completion criterion

Stop when

You reproduce both number pairs (0.76/0.50 and 0.0/192.3) and can name the repair for each of the six leakage kinds without notes.

Mark passed, then open 1.5 Only mark this when you can do it without notes.

Leads to

Comes after

Resources for this unit

  • Hands-On Machine Learning with Scikit-Learn and PyTorch - Chapters 1 and 2
    Aurelien Geron (O'Reilly, 2025)primarycourse
    Read Chapters 1 and 2 of the book, then run notebooks 01 and 02 and use ml-project-checklist.md for framing, data inspection, test-set creation, preprocessing pipelines, cross-validation, error analysis and persistence. Rebuild the workflow on UCI Bike Sharing with a chronological split and prohibit casual and registered when predicting cnt.
  • scikit-learn - Common pitfalls and pipelines
    scikit-learnrequiredreference
    Read Common Pitfalls sections on inconsistent preprocessing and leakage, then Pipeline and ColumnTransformer. Seed global scaling, a target-derived feature and a partition duplicate, and make tests reject each defect.
  • Rules of Machine Learning - first controls
    Google for Developerssupportapplication
    Read Rules 1-5 and 8-9. Turn the existing heuristic into a baseline and test the feature path independently of the learner.
  • UCI Bike Sharing Dataset
    UCI Machine Learning Repositorysupportpractice
    Use hour.csv as the compact integrated dataset. Preserve a raw snapshot and data dictionary, split chronologically, and document why casual and registered are target proxies for cnt.

Also in this section

  • scikit-learn - Cross-validation splitters
    scikit-learnsupportreference
    Use the group-aware and time-aware splitter sections plus GroupKFold and TimeSeriesSplit. Choose from the dependence structure and assert that no prohibited group or future timestamp crosses the boundary.
  • Google ML Problem Framing - framing an ML problem
    Google for Developerssupportapplication
    Read Identify the output you need through Proxy labels and Define the success metrics, including the video-caching threshold analysis, the proxy-issue table, and both Check Your Understanding boxes.

Quick find

Search Michi

Type to search every route, section, unit, topic and resource.

Enter opens the first result Esc closes

Reference

Keyboard shortcuts

n
Continue to the first unit not passed
j / k
Next / previous unit
1 2 3
Toggle learned, practised, passed
/
Open search
?
Show this help
Esc
Close open panels