Feature Engineering: How to Prevent Target Leakage

What is target leakage in feature engineering and how do you prevent it?

Target leakage happens when a feature uses information that wouldn't be available at the moment you make a prediction, such as data recorded after the outcome. It makes a model look accurate in testing and then fail in production. Prevent it by fixing a prediction cutoff time, building features only from data before that cutoff, fitting transformations on training data only, and using time-based or group-based validation splits.

Common sources of leakage

  • Post-outcome fields: a cancellation_reason column when predicting cancellation.
  • Aggregates over the full history, such as a customer's lifetime total spend, including purchases after the prediction date.
  • Scaling, imputation, or target encoding fitted on the whole dataset before splitting.
  • Random splits on time-ordered data, so the model trains on the future and tests on the past.
  • The same customer appearing in both training and test sets.

Build features up to a cutoff

cutoff = pd.Timestamp("2026-09-30")
history = tx[tx["tx_date"] <= cutoff]

features = history.groupby("customer_id").agg(
    last_purchase=("tx_date", "max"),
    tx_count_90d=("tx_date", lambda d: (d > cutoff - pd.Timedelta(days=90)).sum()),
    spend_total=("amount", "sum"),
)
features["recency_days"] = (cutoff - features["last_purchase"]).dt.days

# Label comes from the period AFTER the cutoff
label_window = tx[(tx["tx_date"] > cutoff) & (tx["tx_date"] <= cutoff + pd.Timedelta(days=30))]
features["churned"] = ~features.index.isin(label_window["customer_id"])

Validate the right way

  • Fit transformations inside each training fold, for example with a scikit-learn Pipeline.
  • Use time-based splits for temporal prediction and group splits (GroupKFold) when entities repeat.
  • Be suspicious of a feature that's far more predictive than everything else — it's often leakage.

New features don't automatically improve a model. Keep the ones that help on a leakage-free validation set.

Related skills

Data Analyst Toolkit includes AI-agent skills that follow this method:

More from the blog