Sub topic 3
Target leakage: features you would not have at prediction time
This chapter assumes you can train a scikit-learn classifier and split data into training and test sets. It also assumes you know that held-out scores estimate how a model behaves on new data. Here you will learn to find features that contain the answer, and to remove them.
What target leakage is
Target leakage happens when a feature holds information that exists only because the outcome has already happened. The model learns the shortcut instead of the real signal. Held-out scores look excellent because the test rows contain the same shortcut. In production the feature is empty, late, or different, and accuracy drops.
A proper train-test split does not protect you here. Both sides of the split carry the leak, so the test set agrees with the training set. The problem lies in what the columns mean.
The prediction-time test
For every feature, ask: at the moment the model must make a prediction, would this value already exist, and would it have the same value?
Three situations fail this test:
- The value is created by the outcome. An example is a "refund issued" flag when predicting fraud.
- The value is recorded after the prediction moment. An example is "days in hospital" when predicting readmission at admission.
- The value is a transformed copy of the label, such as a status code that encodes the result.
| Prediction task | Suspect feature | Why it leaks |
|---|---|---|
| Will a customer churn? | `exit_survey_done` | Only customers who cancel receive the survey |
| Will a loan default? | `collections_calls` | Calls start after missed payments |
| Will a patient be readmitted? | `discharge_medication` | Written at discharge, after the stay |
| Will a user click an ad? | `session_ad_clicks` | Includes the click being predicted |
A worked example
The code below builds a churn dataset with two honest features and one leaky feature. The leaky feature is set only when a customer cancels, like an exit survey. It then compares a model with and without it.
import numpy as np
import pandas as pd
from sklearn.ensemble import RandomForestClassifier
from sklearn.metrics import accuracy_score
from sklearn.model_selection import train_test_split
rng = np.random.default_rng(0)
n = 2000
df = pd.DataFrame({
"tenure_months": rng.integers(1, 60, size=n),
"support_tickets": rng.poisson(2, size=n),
})
logit = 0.5 * df["support_tickets"] - 0.03 * df["tenure_months"] - 0.5
df["churned"] = (rng.random(n) < 1 / (1 + np.exp(-logit))).astype(int)
# Leaky: this survey is only sent after a customer cancels
df["exit_survey_done"] = (
(df["churned"] == 1) & (rng.random(n) < 0.9)
).astype(int)
def score(columns):
X_train, X_test, y_train, y_test = train_test_split(
df[columns], df["churned"], random_state=0
)
model = RandomForestClassifier(random_state=0).fit(X_train, y_train)
return accuracy_score(y_test, model.predict(X_test))
honest = ["tenure_months", "support_tickets"]
print("without leak:", score(honest))
print("with leak: ", score(honest + ["exit_survey_done"]))The second score is far higher, typically above 0.9. The first is much lower, because the honest features carry only a modest signal. Nothing in the second run looks wrong. That is why the problem is easy to miss.
Finding the leaky column
You can often find the culprit from the fitted model. A single feature that dominates the importances deserves a question.
X_train, X_test, y_train, y_test = train_test_split(
df[honest + ["exit_survey_done"]], df["churned"], random_state=0
)
model = RandomForestClassifier(random_state=0).fit(X_train, y_train)
for name, weight in sorted(
zip(X_train.columns, model.feature_importances_), key=lambda p: -p[1]
):
print(f"{name:18s} {weight:.2f}")exit_survey_done should rank first by a wide margin. High importance is only a hint. The deciding step is to trace where the column comes from and when it is written.
Common errors
- Trusting column names. A column called
statusmay be updated after the outcome. Read the data dictionary or ask the data owner when each field is written. - Using a snapshot taken after the fact. A table that holds each customer's current state describes them after the outcome. Rebuild features as they stood at the prediction date.
- Aggregates that include the outcome. A "total purchases this month" feature includes the purchase you are trying to predict if the window overlaps it.
- Dropping only the obvious column. Features derived from the leaky one, such as ratios and flags, still leak. Remove the whole family.
- Fixing it by tuning. A leaky model needs a different feature set, not different hyperparameters.
Exercise
Exercise
You are predicting whether an online order will be returned, and the model runs when the customer places the order. Your table has order_total, num_items, customer_age_days, and return_label_printed. Which feature should you remove, and why?
Show answer
Remove return_label_printed. A return label is created only after the customer starts a return, so it exists because of the outcome and would not be available when the order is placed. The other three are known at order time and are safe.