Sub topic 3
Target leakage: features you would not have at prediction time
Prerequisites and scope
This chapter assumes you know supervised learning basics (features, labels, train and test sets), can read Python and NumPy, and have used scikit-learn estimators with fit, transform, and predict. The previous chapters defined data leakage and showed how to split data into train, validation, and test sets. Here we look at the first and most common kind of leakage: target leakage.
Target leakage happens when a feature contains information that would not exist at the moment the model has to make a prediction. The feature may be a copy of the label, a consequence of the label, or a value recorded after the outcome was known. Splitting the data correctly does not fix it. Train and test rows both contain the leaking column, so the model scores well on both and fails once it is deployed.
The one question to ask about every feature
For each feature, ask this question:
> Will this exact value be available, in this exact form, at the moment the prediction is made?
That is a question about time and process, not about statistics. A feature can be strongly predictive and still be unusable, because the strength comes from the future. Answering the question needs knowledge of the business process that produces the data. A column's name often hides when it is filled in.
Consider a model that predicts whether a customer will cancel a subscription in the next 30 days. These columns look reasonable:
| Column | Available at prediction time? | Verdict |
|---|---|---|
| `plan_type` | Yes, set at signup | Safe |
| `logins_last_30d` | Yes, if computed up to the prediction date | Safe |
| `support_tickets_total` | Depends on whether it counts tickets after the prediction date | Check how it is computed |
| `cancellation_reason` | No, only filled when the customer cancels | Leak |
| `account_status` | No, it becomes "closed" after cancelling | Leak |
| `refund_issued` | No, usually a consequence of cancelling | Leak |
The first two rows are ordinary. The last three are the danger. cancellation_reason is empty for everyone who stayed, so a tree can split on "is it empty?" and get near-perfect accuracy.
Three common forms of target leakage
Direct copies and near copies of the label
The simplest case is a column that is the label in another form. Examples are a churned_flag next to a churn_date, or a loan_status column used to predict default. These are easy to catch when you scan column names, but they hide behind encodings, such as a numeric risk_code that was derived from the label by another team.
Consequences of the outcome
A consequence is recorded because the event happened. In a hospital setting, "received treatment X" can predict "diagnosed with condition X" almost perfectly, because treatment follows diagnosis. In fraud detection, "chargeback filed" follows fraud. The model learns the paperwork, not the risk.
Values updated after the prediction time
Some columns exist at prediction time but hold a different value later. A table row for a customer may be overwritten as the customer's state changes. If you export the table today to train a model that predicts last month's events, you read today's value, which already reflects what happened. Typical examples are total_purchases as a running total, last_login_date, and credit_score stored as a single current value.
This case is a snapshot problem. The fix is to rebuild each feature "as of" the prediction date, using event logs or a feature store that keeps history.
A worked example you can run
The code below builds a small churn data set. One feature, cancel_reason_filled, is a consequence of the label. We compare a model with and without it.
import numpy as np
import pandas as pd
from sklearn.ensemble import RandomForestClassifier
from sklearn.model_selection import train_test_split
from sklearn.metrics import roc_auc_score
rng = np.random.default_rng(0)
n = 2000
logins = rng.poisson(10, size=n)
tenure_months = rng.integers(1, 48, size=n)
# Churn depends weakly on the honest features
logit = -0.15 * logins - 0.03 * tenure_months + 0.8
churned = rng.random(n) < 1 / (1 + np.exp(-logit))
# Consequence of the label: only churned customers get a reason recorded
cancel_reason_filled = churned.astype(int)
df = pd.DataFrame(
{
"logins": logins,
"tenure_months": tenure_months,
"cancel_reason_filled": cancel_reason_filled,
"churned": churned.astype(int),
}
)
def auc_for(columns):
X_train, X_test, y_train, y_test = train_test_split(
df[columns], df["churned"], test_size=0.25, random_state=0
)
model = RandomForestClassifier(n_estimators=200, random_state=0)
model.fit(X_train, y_train)
return roc_auc_score(y_test, model.predict_proba(X_test)[:, 1])
honest = auc_for(["logins", "tenure_months"])
leaky = auc_for(["logins", "tenure_months", "cancel_reason_filled"])
print(f"honest AUC: {honest:.3f}")
print(f"leaky AUC: {leaky:.3f}")The honest model scores a modest AUC, a little above 0.5 because the signal is weak. The leaky model scores close to 1.0. The split here is correct and the test set is untouched, yet the score is meaningless. In production, cancel_reason_filled is always 0 at prediction time, because nobody has cancelled yet, and the model collapses.
How the leak travels through the pipeline
The diagram shows why the leak survives a clean evaluation but breaks in production.
Leakage that comes from how you build the data set
Leaks often enter at the data collection stage rather than in a single column.
- Joins that reach into the future. Joining a customer table to an events table on
customer_idalone pulls in events after the prediction date. Add a time condition so only events before the prediction time are joined. - Aggregates over the whole history.
mean_order_valuecomputed over all rows includes orders that occurred after the label was determined. Compute it over a window ending at the prediction date. - Label-derived filters. If you keep only customers with at least 6 months of history, and the customers who churned early were dropped for being short-lived, the filter itself depends on the outcome and shifts the data set.
- Missingness that encodes the outcome. A null in
cancel_reasonmeans "did not cancel". Tree models use missing-value patterns freely. Check whether the pattern of nulls differs by label. - Identifiers. Row IDs, ticket numbers, and file names can encode order or class, for example when positive cases were exported first and received the lowest IDs.
Here is a point-in-time join in pandas. It attaches to each prediction row only the events that happened before the prediction date.
import pandas as pd
predictions = pd.DataFrame(
{
"customer_id": [1, 1, 2],
"prediction_date": pd.to_datetime(["2024-03-01", "2024-04-01", "2024-03-01"]),
}
)
events = pd.DataFrame(
{
"customer_id": [1, 1, 1, 2],
"event_date": pd.to_datetime(
["2024-02-10", "2024-03-15", "2024-04-20", "2024-02-25"]
),
"amount": [20.0, 35.0, 50.0, 12.0],
}
)
# Wrong: every event for the customer, including future ones
naive = (
predictions.merge(events, on="customer_id")
.groupby(["customer_id", "prediction_date"])["amount"]
.sum()
)
# Right: keep only events strictly before the prediction date
joined = predictions.merge(events, on="customer_id")
joined = joined[joined["event_date"] < joined["prediction_date"]]
as_of = joined.groupby(["customer_id", "prediction_date"])["amount"].sum()
print(naive)
print(as_of)For customer 1 on 2024-03-01, the naive total is 105, which includes events in March and April. The as-of total is 20. Note that customer 1 on 2024-04-01 correctly gets 55, and a customer with no earlier events drops out of the grouped result, so you may need a reindex or fillna(0) to keep every prediction row.
Spotting target leakage in a trained model
You usually find these leaks through symptoms, which a later chapter treats in full. Three signals are worth checking now.
- A score that is too good. An AUC above 0.95 on a problem that experts find hard is a warning, not a result.
- One feature that dominates. If a single column carries most of the importance, ask why.
- A single-feature model that works too well. Train a shallow tree on each feature alone and rank the scores. A feature that nearly solves the task by itself needs an explanation.
The snippet below applies the third check to the data frame from the worked example.
from sklearn.tree import DecisionTreeClassifier
from sklearn.model_selection import cross_val_score
features = ["logins", "tenure_months", "cancel_reason_filled"]
for col in features:
tree = DecisionTreeClassifier(max_depth=3, random_state=0)
score = cross_val_score(tree, df[[col]], df["churned"], cv=5, scoring="roc_auc").mean()
print(f"{col:22s} single-feature AUC = {score:.3f}")cancel_reason_filled reaches an AUC of 1.0 on its own. That is the cue to trace where the column comes from.
Edge cases and judgment calls
- A feature is available, but late. Some data arrives with a delay, for example lab results that take two days. Use the value only if the delay is built into your training data, so that a row at time t only sees values that would have arrived by t.
- A feature is a proxy for the label, but legitimately known. A prior-year default flag predicts this year's default and is available at prediction time. It is a strong honest feature, not leakage. The test is timing, not strength.
- The label is defined by a feature. If "high risk" is defined as
score > 700, thenscoreis the label in disguise. Remove it or redefine the task. - Imputed or corrected values. Data cleaning done after the outcome, such as an analyst fixing the record of a churned customer, can inject outcome information. Ask whether corrections are applied before or after the prediction time.
- Features that exist in training but not in serving. A pipeline that can't compute a feature at serving time reveals a leak early. Treat "we can't produce this in production" as evidence of leakage, not just an engineering nuisance.
Fixing the problem
- Remove the leaking column, or rebuild it as of the prediction time.
- Re-run the evaluation and expect the score to fall. A drop is the correct outcome, not a regression.
- Record the decision in a data dictionary, with a column for "known at prediction time" and the source system.
- Add a check that fails when a new column appears without that annotation.
Dropping a feature is cheap. Shipping a model that relied on it is expensive.
Exercise
A hospital model predicts whether a patient will develop sepsis during their stay. A data scientist includes the feature antibiotic_given_iv, taken from the final discharge record. The test AUC is 0.97. Explain why this feature is likely a leak and describe two ways to check or fix it.
Show answer
Antibiotics are often given because sepsis was suspected or diagnosed, so the feature is a consequence of the outcome and may be recorded after the prediction time. Because the discharge record is finalized after the stay, it also reflects events that happen after the point at which the model must predict. To check, compare the timestamp of the antibiotic order with the prediction time and test a single-feature model to see if it nearly solves the task alone. To fix, either remove the feature or rebuild it as of the prediction time, counting only antibiotic orders placed before that moment, and then re-evaluate expecting a lower AUC.
Exercise
In the point-in-time join example, why does the filter use event_date < prediction_date instead of <=, and what could go wrong if prediction rows are created at the end of the day?
Show answer
The strict inequality excludes events that occur at the prediction moment, since an event on the same date may be recorded after the model would have run. If predictions are made at the end of a day, same-day events are known by then and <= may be correct, so the right comparison depends on the actual prediction timestamp. Using timestamps with a time of day, rather than dates alone, removes the ambiguity. Choosing the wrong side either leaks same-day events into training or discards information that production would have.