Data leakage

When information from the future or the target sneaks into training, scores lie.

Lesson 10 of 6612 minIntermediate

You will learn to

  • Recognise target leakage and train-test contamination
  • Explain why preprocessing must be fitted on training rows only, inside each fold
  • Use the leakage signal in the data profile

Before this lesson

Intuition

Imagine a teacher who hands out the exam questions the evening before. Everyone scores 100%, and the exam tells you nothing about what students know. Data leakage is the same failure in machine learning: the model gets, during training or evaluation, information that it will not have when it makes real predictions. The score looks excellent. The model is not.

Leakage has three common forms.

  • Target leakage. A feature is recorded after, or because of, the outcome. Examples: a "refund issued" column when predicting fraud; a "discharge medication" column when predicting hospital readmission; an invoice number assigned only to customers who paid.
  • Train-test contamination. Something learned from the test rows reaches the training process. The classic case is fitting a scaler, an imputer or a feature selector on the whole dataset before splitting.
  • Group and time leakage. Related rows are on both sides of a split (several visits of one patient), or future rows are used to predict the past.

The question to ask of every column and every step is the same: would I have this exact information at the moment of a real prediction?

Picture it

Leaky: fit before splittingAll rowsFit scaler on all rowsSplitCorrect: split, then fit on train onlySplitFit scaler on trainApply to test
Top: fitting the scaler before the split lets the test rows shape the training data. Bottom: split first, learn the statistics from the training rows only, then apply them unchanged to the test rows.

The leaky order looks harmless because no label is involved. It still leaks: the mean and spread that the training rows are scaled with already contain the test rows.

The math

Let a preprocessing step learn parameters θ\theta from data, for example the mean and standard deviation of a column. The honest procedure learns θ\theta from the training rows DtrainD_{\text{train}} only and applies the same fixed map to new rows:

θ=g(Dtrain),x′=hθ(x)\theta = g(D_{\text{train}}), \qquad x' = h_{\theta}(x)

The leaky procedure uses θ=g(Dtrain∪Dtest)\theta = g(D_{\text{train}} \cup D_{\text{test}}). The test rows now influence the model's inputs, so the test score is no longer an estimate for unseen data. For a mean or a standard deviation the effect is usually small; for a feature selector or a target encoder, which look at the labels, it can be large.

With cross-validation the rule applies to every fold: for each round, gg sees only the k−1k-1 training folds of that round, never the validation fold.

To detect suspicious features, mlflow measures how strongly each feature is associated with the target on a scale from 0 to 1 (a normalized mutual-information style measure for categories and binned numbers). A feature that scores close to 1 against the target almost determines it. That is rare in honest data.

Worked example

Two small computations, both done with NumPy.

Contaminated scaling. The training values of a column are 10, 12, 14 (mean 12, standard deviation 1.63). One test value is 100.

  • Honest: the test value becomes (100−12)/1.63≈53.9(100 - 12)/1.63 \approx 53.9. It is clearly huge, so the model is warned that the row is far outside what it has seen.
  • Leaky: the scaler is fitted on all four values (mean 34, standard deviation 38.1). The test value becomes 1.73, an ordinary-looking number, and the three training values become about -0.63, -0.58 and -0.52, squeezed together. The pipeline has hidden the outlier and distorted the training data, using knowledge of the test row.

Target leakage. A telecom dataset has 5,000 customers and a target churned. A column retention_offer_accepted is filled in only after the customer called to cancel. Its association with the target scores 0.97. A column monthly_charges scores 0.12. A model trained with both reaches near-perfect validation scores, but at prediction time (before the customer cancels) retention_offer_accepted is always empty. (The numbers in this paragraph are illustrative.) The fix is not a better model: drop the column.

How mlflow does it

  • Leakage signal. The data profile checks each feature against the target. A feature whose association is 0.80 or higher is reported as possible leakage, with the column, the strength and the measure. The warning is advisory: you decide whether the column is known at prediction time. No claim is made for datasets under 20 rows, and a large dataset is scored on a stratified sample of up to 50,000 rows; the card says when only a subset was scored. Free-text and high-cardinality categorical columns are skipped.
  • Where to see it. Open Data, open a dataset with Explore, and read the Quality tab: the Target leakage card lists the strongest associations, and Quality score counts leakage as one of its components.
  • Steps are fitted inside each fold. In Pipeline Studio, every step you add is part of the model. It is fitted on the training rows of each fold and applied to the rows being scored, so the scaling example above cannot happen in a pipeline.
  • Group leakage. A Group column in the Cross-validation card keeps every group on one side of the split and of every fold. See Cross-validation.

Common mistakes

  • Preprocessing the file before uploading it. Scaling, imputing or selecting features in a spreadsheet or a notebook, then uploading, leaks. Do it as pipeline steps.
  • Trusting a too-good score. An AUC of 0.99 on a hard problem is a reason to look for leakage before celebrating. Check the strongest features first.
  • Keeping identifiers and timestamps that encode the outcome. An ID assigned in order of signup, or a "last updated" time set when a case closes, can reveal the label. Ask how each column is created.
  • Random splits on related rows. Repeated measurements, same-user events and time series need group or time-ordered splits.
  • Target encoding on the full data. An encoding built from the target must be fitted per fold, as in Encoding categorical variables.
  • Treating the profile warning as a verdict. A high association can also be a genuinely strong predictor. Decide by asking when the value becomes known.

Try it in mlflow

Look for leakage warnings

  1. Open Data and pick a dataset with a target column.
  2. Click Explore and open the Quality tab.
  3. Read the Target leakage card: the strongest associations with the target, and any warning.
  4. For each flagged column, ask whether its value is known at the moment you would make a prediction.
Open in mlflow

Read in the docs

Check your understanding

  1. 1. A churn model uses a column called cancellation_date, filled in only for customers who left. Validation accuracy is 99%. What is the most likely explanation?
  2. 2. You standardize every column using the mean and standard deviation of the full dataset, then split into train and test. What is wrong?
  3. 3. Your rows are repeated measurements of 200 machines, and the model will run on new machines. Random k-fold gives AUC 0.95; grouping by machine gives 0.78. Which score do you trust?