Feature engineering & data leakage

In one sentence

Turn raw events into signals a model can use (scaled numbers, encoded categories, crosses, time-window aggregates) while making sure no feature peeks at the label or the future.

Analogy: Leakage is a student who saw the answer key: a perfect score on the practice exam, then a fail on the real one. A time-based split locks the key away until the exam is over.

Every arrow points forward in time: features use only the past, and transforms are fit on the training window and merely applied to the future.

How it works

  • Standardize numbers for linear models and neural nets (trees don't care); log1p heavy tails like amounts.
  • Encode categories by cardinality: one-hot for dozens, target encoding or hashing beyond, embeddings for huge ID spaces.
  • Time-window aggregates, like a card's transactions in the last 1h/24h/7d, are often the strongest features.
  • Data leakage is training information that won't exist at prediction time; a suspiciously great offline score is the alarm.
  • Compute features as of the event timestamp, split by time, and fit transforms on the training window only.

Check yourself

Answer to mark it learned; your answers aren't scored.

You review features for a fraud model that scores each card transaction at authorization time. Which one must you drop or rebuild?

Go deeper

Full explanation

Feature engineering turns raw data into inputs that make the pattern easy to learn.

  • Numbers: standardize for linear models, neural nets and kNN (trees don't care); log1p heavy tails like amounts and counts; clip outliers.
  • Categories: one-hot for a few dozen values; target encoding (category → smoothed mean label, computed out-of-fold) for high cardinality; the hashing trick for open vocabularies; learned embeddings for huge ID spaces in neural nets.
  • Crosses: country × device lets a linear model learn interactions.
  • Time-window aggregates: a card's transactions in the last 1h/24h/7d, a user's 30-day CTR; often the strongest features in fraud and ads.
  • Text: TF-IDF, sentence embeddings or LLM-extracted attributes.

Data leakage is information in training that won't exist at prediction time:

  1. Target leakage: a feature that encodes the outcome (chargeback_count when predicting fraud).
  2. Contamination: scalers or encoders fit on all data before the split; the same user in train and test.
  3. Time travel: aggregates computed from today's table, or random splits on time-ordered data.

The cure: compute every feature as of the event timestamp (point-in-time joins, a Feature stores), split by time (and by user), and fit all transforms on the training window only. A suspiciously great offline score is a leakage alarm.

Code Point-in-time features, time split, leak-free pipeline
pythonPoint-in-time features, time split, leak-free pipeline
import numpy as np
from sklearn.compose import ColumnTransformer
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import average_precision_score
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import FunctionTransformer, OneHotEncoder, StandardScaler, TargetEncoder

tx = load_transactions().sort_values("ts")  # card_id, merchant_id, country, amount, ts, is_fraud

# Point-in-time aggregate: this card's transactions in the 24h BEFORE each one
tx["n_tx_24h"] = (tx.set_index("ts").groupby("card_id")["amount"]
                    .transform(lambda s: s.rolling("24h", closed="left").count())
                    .fillna(0).to_numpy())

# Time-based split: train on the past, validate on the future (never a random split)
cut = tx["ts"].quantile(0.8)
train, valid = tx[tx["ts"] < cut], tx[tx["ts"] >= cut]
cols = ["amount", "n_tx_24h", "country", "merchant_id"]

features = ColumnTransformer([
    ("num", make_pipeline(FunctionTransformer(np.log1p), StandardScaler()), ["amount", "n_tx_24h"]),
    ("low_card", OneHotEncoder(handle_unknown="ignore"), ["country"]),
    ("high_card", TargetEncoder(), ["merchant_id"]),  # cross-fitted (5 folds) inside fit
])
model = make_pipeline(features, LogisticRegression(max_iter=1000))
model.fit(train[cols], train["is_fraud"])  # every encoder sees the training window only

p = model.predict_proba(valid[cols])[:, 1]
print("PR-AUC on the future:", average_precision_score(valid["is_fraud"], p))
Real example

A fraud model scores 0.99 ROC-AUC offline but ~0.70 in shadow mode. SHAP shows the top feature is card_chargebacks_30d, computed from today's table: for fraudulent training rows it already counted the chargeback filed weeks after the transaction. The team recomputes every aggregate as of the transaction timestamp, replaces the random split with train on January–September and validate on October, and moves the target encoder inside the pipeline. Offline AUC drops to 0.86, and now it matches production.

Trade-offs +3 · −3

+ You gain

  • Usually the biggest lever on tabular models, often bigger than switching algorithms.
  • Encodes domain knowledge (velocity, recency, ratios) that a model can't find in single raw rows.
  • Simple models on good features are fast, debuggable and explainable.

− You pay

  • Manual and domain-specific; hard to reuse across teams without a feature store.
  • Each feature must be computed identically offline and online, or you get training-serving skew.
  • More features mean more leakage surface and more pipelines to monitor.

Use it when

Always for tabular models (GBDT, linear); with deep models too, for aggregates, recency and business signals the network can't see in a single raw event.

Avoid it when

Hand-crafting features from raw text, images or audio: pretrained encoders learn better ones end to end. Engineer the context around them instead.

Numbers to know 5
  • Kapoor & Narayanan: leakage affected ~300 published papers across 17 scientific fields (294 in the 2023 Patterns version).
  • Facebook ads (He et al., 2014): "the most important thing is to have the right features"; historical user and ad features dominated.
  • Rule of thumb: one-hot up to ~tens of categories; beyond that, target encoding, hashing or embeddings.
  • Rule of thumb (Google, TensorFlow feature columns): embedding size ≈ fourth root of the category count, e.g. 10,000 → 10.
  • scikit-learn's TargetEncoder (≥ 1.3) cross-fits with 5 folds in fit_transform, so no row's encoding sees its own label.
Common pitfalls 4
  • Fitting scalers, imputers or target encoders on the full dataset before splitting.
  • Random train/test splits on time-ordered data: the model trains on the future.
  • The same user or session on both sides of the split: the model memorizes users. Use group splits.
  • Aggregates computed from today's snapshot instead of as of each event's timestamp.
Interview questions 2

Answer out loud first, then reveal.

Your model shows 0.99 AUC offline and disappoints in production. How do you debug it?Show answer

I assume leakage until proven otherwise. First, the top features by SHAP: for each one I ask whether that exact value would exist at prediction time. Post-outcome fields and aggregates computed from today's tables are the usual culprits. Second, the split: random rows on time-ordered data, or the same user on both sides, inflate scores, so I re-run with a time split and a group split. Third, preprocessing fit before the split. If it survives all that, I compare offline and online feature values for the same requests to rule out training-serving skew.

How do you encode a categorical feature with a million values, like merchant_id?Show answer

One-hot gives a million sparse columns and learns nothing for rare merchants. My options: the hashing trick into, say, 2^20 buckets, with no vocabulary to maintain but some collisions; smoothed target encoding computed out-of-fold, compact and great with GBDTs, but it leaks if done naively and drifts as rates change; or a learned embedding in a neural net, best with lots of data but cold for new IDs. With a GBDT I'd use out-of-fold target encoding plus a frequency count; with a deep model, hashed embeddings. Either way, rare and unseen values go to an 'other' bucket.