Sub topic 10
Leakage in feature engineering and encodings
This chapter assumes you know scikit-learn estimators (fit, transform, predict) and pipelines, and that you have seen preprocessing leakage and cross-validation leakage in earlier chapters. Here the same rule is applied to features you build yourself: aggregates, encodings, lag features, and resampling.
Why engineered features leak
A feature is any value computed from data and handed to the model. Two questions decide whether it leaks:
- Does the computation use the label of the row being encoded, or labels of held-out rows?
- Does it use rows that would not exist at prediction time, such as future rows or test rows?
If either answer is yes, the training score reflects information the model will not have in production. Built-in scalers are easy to put in a pipeline. Hand-written features are riskier because they often live in a pandas script that runs before any split.
The rule from earlier chapters still applies: any statistic learned from data is a fitted parameter. It must be fitted on the training rows of the current split, then applied unchanged to other rows.
Target encoding
Target encoding replaces a categorical value with a statistic of the target for that category, usually the mean. It is useful for high-cardinality columns such as user IDs, ZIP codes, or product codes, where one-hot encoding creates thousands of columns.
The naive version leaks even when you fit it on the training split only. Each training row's own label is part of its category mean. If a category has one training row, the encoded value equals the label exactly.
The following code uses random labels, so no honest model can beat 0.5 accuracy:
import numpy as np
import pandas as pd
from sklearn.ensemble import RandomForestClassifier
from sklearn.model_selection import train_test_split
rng = np.random.default_rng(0)
n = 2000
df = pd.DataFrame({
"user": rng.integers(0, 1000, size=n),
"y": rng.integers(0, 2, size=n), # labels are pure noise
})
train, test = train_test_split(df, random_state=0)
# Leaky: each training row's label is inside its own category mean
means = train.groupby("user")["y"].mean()
prior = train["y"].mean()
train_enc = train["user"].map(means).to_frame("enc")
test_enc = test["user"].map(means).fillna(prior).to_frame("enc")
model = RandomForestClassifier(random_state=0).fit(train_enc, train["y"])
print("train accuracy:", model.score(train_enc, train["y"]))
print("test accuracy:", model.score(test_enc, test["y"]))Training accuracy is far above 0.5 and test accuracy is near 0.5. The model learned to read the label back out of the feature. The test set is not contaminated here. The failure is that the training feature is unrepresentative of the feature the model sees on new rows, so the model learns the wrong thing and any validation scheme that reuses those training features reports inflated scores.
Out-of-fold encoding
The standard fix is cross-fitting. Split the training rows into folds. Encode each fold using category means computed from the other folds only. No row ever contributes to its own encoding. Test rows are encoded with statistics from the whole training set.
Scikit-learn 1.3 and later provides TargetEncoder, which does this internally. Its fit_transform cross-fits the training data. Its transform uses statistics from the full fit. It also shrinks rare categories toward the global mean (smooth="auto"). Put it in a pipeline so cross-validation refits it in every fold:
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 = 2000
df = pd.DataFrame({
"user": rng.integers(0, 1000, size=n),
"y": rng.integers(0, 2, size=n),
})
X, y = df[["user"]], df["y"]
pipe = make_pipeline(TargetEncoder(random_state=0), LogisticRegression())
print(cross_val_score(pipe, X, y, cv=5).mean()) # close to 0.5, as it should beFrequency and count encodings
Counting how often each category appears does not use the target, so it is not target leakage. It can still leak through the split. If you count categories over the full dataset, a test row's count includes other test rows. The feature then encodes how common a value is across the test set, which you would not know at prediction time for a single incoming row. Fit the counts on the training split. Treat unseen categories explicitly, for example with a count of 0 or an "unknown" bucket.
Aggregates and group statistics
Features like "average purchase amount per customer" or "ratio of this price to the category median" are group statistics. Computing them with groupby(...).transform("mean") on the whole dataframe has two problems:
- The statistic includes test rows.
- If the quantity being aggregated is the target (or is derived from it), each row's own label is included.
Compute the statistic from training rows and map it onto both splits:
import pandas as pd
from sklearn.model_selection import train_test_split
df = pd.DataFrame({
"category": ["a", "a", "b", "b", "b", "c", "c", "a"],
"price": [10, 12, 20, 22, 18, 5, 7, 11],
"bought": [0, 1, 1, 1, 0, 0, 0, 1],
})
train, test = train_test_split(df, test_size=0.25, random_state=0)
median_price = train.groupby("category")["price"].median()
global_median = train["price"].median()
for part in (train, test):
ref = part["category"].map(median_price).fillna(global_median)
part["price_vs_median"] = part["price"] / ref # test rows use training mediansIf you need this inside cross-validation, write the logic as a custom transformer with fit and transform methods and place it in a Pipeline. The statistics are then learned from each fold's training part.
Time-based features
Lag and rolling features leak when the window includes the row being predicted, or any later row. A rolling mean with default settings includes the current value. If the target is that value, the feature contains the answer.
import pandas as pd
s = pd.DataFrame(
{"sales": [10, 12, 11, 15, 14, 18]},
index=pd.date_range("2026-01-01", periods=6),
)
# Leaky when predicting today's sales: the window includes today
s["leaky_mean3"] = s["sales"].rolling(3).mean()
# Correct: shift first, so only earlier days are in the window
s["mean3"] = s["sales"].shift(1).rolling(3).mean()
print(s)Features such as "days until the next event" or "total spend in the following 30 days" look forward by construction. Ask of every time-based feature what timestamp it would be computed at in production. Use TimeSeriesSplit for evaluation, as covered in the temporal leakage chapter. Do not use centered windows, backward fills, or interpolation across the split boundary. Interpolation can pull values from after the cutoff into earlier rows.
Resampling and augmentation
Oversampling (SMOTE, random duplication) and augmentation create new rows from existing ones. If you do it before splitting, copies or near-copies of one row land on both sides of the split. This is duplicate leakage produced by your own code. Split first, resample only the training part, and never resample validation or test data. With scikit-learn-style tooling, use imblearn.pipeline.Pipeline, which applies samplers only during fit. The standard sklearn.pipeline.Pipeline does not accept samplers.
Other fitted feature steps
Several steps hide a fit that is easy to run on all the data:
| Step | What it learns | Leaky habit | Safe habit |
|---|---|---|---|
| Imputation | Mean, median, or model of missing values | Impute the full table, then split | Pipeline with an imputer |
| Binning | Quantile edges | `pd.qcut` on the full column | `KBinsDiscretizer` in a pipeline |
| Text vectorizing | Vocabulary, IDF weights | Fit `TfidfVectorizer` on all documents | Fit on training documents only |
| Dimensionality reduction | Principal components | PCA on all rows | PCA step inside the pipeline |
| Outlier clipping | Percentile caps | Compute caps on all rows | Learn caps on training rows |
| Learned embeddings | Vectors trained on text or IDs | Train on a corpus that includes test items | Train on training data, or use a pretrained model that predates your test data |
Features derived from the label's consequences
Feature engineering can also leak through meaning rather than computation. This is target leakage by construction. Examples:
- A "days since last contact" column that is updated after a sale happens.
- A "refund issued" flag when predicting fraud.
- Features aggregated over a period that ends after the prediction time, such as a monthly total used to predict an event on day 5.
For each engineered feature, write down the event time of its newest input and compare it to the prediction time. If the newest input is later, the feature leaks, regardless of how carefully the code is split.
A review routine for engineered features
- List every column that is not raw input and name the rows and columns it was computed from.
- Mark any feature that uses the target, directly or through another feature.
- Mark any feature whose computation spans more than one row, such as a group statistic, rolling window, or count.
- For each marked feature, confirm it is fitted inside the training part of each split, usually in a
Pipeline. - Compare the training score and the pipeline cross-validation score. A large gap that shrinks when you remove one feature points to that feature.
Exercise
A colleague computes df["city_rate"] = df.groupby("city")["churned"].transform("mean") on the full dataframe, then runs train_test_split and fits a model. Name two separate ways this leaks, and say how you would fix it.
Show answer
First, the city mean includes the labels of the test rows, so test labels influence training features. Second, each training row's own label is part of its city mean, so small cities give the model a near copy of the answer. Fix both by splitting first, then computing the encoding with out-of-fold means on training rows (or TargetEncoder inside a Pipeline). Encode test rows with means from all training rows only.
Exercise
You build a feature rolling_mean_7 = df["demand"].rolling(7).mean() to predict demand for the same day. Why does it leak, and what is the one-line change that fixes it?
Show answer
The window of 7 values includes the current day's demand, which is the target. Shifting by one row first removes it: df["demand"].shift(1).rolling(7).mean().
Exercise
Why must SMOTE be applied only to the training part of each cross-validation fold, and which pipeline class lets you do that?
Show answer
SMOTE creates synthetic rows from nearby training rows. If it runs before splitting, synthetic rows and their source rows end up in both training and validation data, which inflates the score. imblearn.pipeline.Pipeline applies the sampler only while fitting, so each fold resamples its own training part and leaves the validation part untouched.