Sub topic 10
Leakage in feature engineering and encodings
This chapter assumes you know the earlier chapters on preprocessing leakage and pipelines. You should be comfortable with scikit-learn's fit and transform, Pipeline, and cross-validation.
Why feature engineering leaks
Feature engineering creates new columns from existing data. Any step that learns a value from rows, such as a mean, a count, a category ranking, or a bin edge, behaves like a model fitted on those rows. If it learned from rows that later appear in a validation or test fold, the new feature carries outside information. The rule is the same as for scaling: learn on training rows only, then apply to held-out rows.
Feature engineering has a second risk that scaling does not. Some features are built from the label itself, so a mistake leaks the answer directly.
Common leaky constructions
| Feature | How it leaks | Safe version |
|---|---|---|
| Target encoding (mean of `y` per category) | A row's own label is part of its category mean | Cross-fitted encoding inside a pipeline |
| Group aggregates (average spend per customer) | The average includes rows from the test fold | Compute from training rows only |
| Frequency or count encoding | Counts include test rows | Fit counts on the training split |
| Quantile bins and imputation values | Edges and fill values use test rows | Fit inside the pipeline |
| Rolling or lag features | Windows reach into future rows | Use only past rows, and split by time |
Target encoding: the clearest case
Target encoding replaces a category with the average label of that category. If a category has only a few rows, each row's own label makes up much of the average. The model can read the answer straight from the feature.
The code below uses pure noise labels. A correct evaluation should score about 0.5. It needs scikit-learn 1.3 or later for TargetEncoder.
import numpy as np
import pandas as pd
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import cross_val_score
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import TargetEncoder
rng = np.random.default_rng(0)
n = 1000
city = pd.Series(rng.integers(0, 300, size=n).astype(str), name="city")
y = rng.integers(0, 2, size=n) # labels are pure noise
# Leaky: each row's own label is inside its category mean
leaky_feature = pd.Series(y).groupby(city).transform("mean").to_frame("city_te")
leaky = cross_val_score(LogisticRegression(), leaky_feature, y, cv=5).mean()
# Correct: the encoder is refit on each training fold.
# TargetEncoder also cross-fits internally, so a row never sees its own label.
pipe = make_pipeline(TargetEncoder(random_state=0), LogisticRegression())
honest = cross_val_score(pipe, city.to_frame(), y, cv=5).mean()
print(f"leaky={leaky:.2f} honest={honest:.2f}")The leaky score is typically well above 0.5, and the pipeline score stays near 0.5. There are two separate fixes here, and you need both:
- Fit the encoder only on training rows. The pipeline does this in every fold.
- Avoid encoding a training row with its own label.
TargetEncoder.fit_transformuses internal cross-fitting for this. If you write the encoding by hand, compute it out-of-fold or add smoothing.
Group aggregates and time-based features
Features such as "mean purchase amount per customer" or "number of orders in the dataset" use many rows to describe one row. Compute them in two steps:
- Split the data first.
- Build the aggregate from training rows. Look up each held-out row's value from that training table.
Customers who appear only in the held-out set need a fallback, such as the global training mean. Treat this as a normal case. A feature that is always present in your evaluation but missing for new customers in production is itself a mismatch.
For time-ordered data, the aggregate must respect time. A "customer average" for a January row must not include March purchases. Use expanding or rolling windows that look backward only, and combine them with a time-aware split like the one in the temporal leakage chapter.
A practical test for each feature
Ask two questions about every engineered column:
- Does it learn anything from data? Means, counts, rankings, bin edges, and imputed values all do. If yes, it must be fitted inside the training fold, ideally as a pipeline step.
- Would I be able to compute it at prediction time for a brand-new row? If it needs the label, or data that arrives later, it is target leakage.
Stateless transforms, such as taking a logarithm or extracting the day of week, learn nothing and are safe to apply before splitting.
Exercise
A teammate adds a column avg_price_by_store by running df.groupby("store")["price"].transform("mean") on the full dataset, then splits into train and test. The model predicts price. Name the two kinds of leakage involved and describe a fix.
Show answer
The feature uses the target (price), so it is target leakage, and each row's own price is part of its store average. It is also preprocessing-style leakage, because the averages include test rows. The fix is to split first and compute store averages from training rows only. For training rows, use out-of-fold averages, so a row's own price is excluded. Fall back to the global training mean for stores not seen in training. Wrapping the logic in a pipeline step makes cross-validation refit it in every fold.