Sub topic 8
Avoiding target leakage and look-ahead bias
This chapter assumes you can build lag and rolling features in pandas and have seen a chronological train/test split. It covers how future information gets into a feature table and how to catch it.
What leakage is
Target leakage means a feature contains information about the value you are trying to predict. Look-ahead bias is the time-series version: a feature for time t uses data from after the moment you would actually have made the forecast.
A leaky model scores well in validation and fails in production. In production the future values are not there.
The rule is that a row for time t may use only information available when the forecast is made.
Common sources of leakage
- Rolling windows that include the current value.
s.rolling(7).mean()at rowtaverages the target itself. Shift first, then roll. - Centered windows.
rolling(7, center=True)uses three future values. - Statistics fitted on all the data. Scalers, target encodings and imputation values must be computed on the training part only.
- Random splits. Shuffled rows put neighbouring days in both train and test.
- Lags that reach into the validation block. With a 7-day lag, the first validation rows have features built from training-period targets, and the reverse is also a risk when the window overlaps. A
gapinTimeSeriesSplitseparates the blocks. - Features that are not known at forecast time. Examples are today's final sales total or a weather observation recorded after the forecast is issued.
A mechanical leak test
You can test a feature function directly. Change one value in the series. Features at that row and at earlier rows must not change.
import numpy as np
import pandas as pd
idx = pd.date_range('2024-01-01', periods=60, freq='D')
s = pd.Series(np.random.default_rng(0).normal(size=60), index=idx)
def leaks(feature_fn, s, k=40):
base = feature_fn(s)
changed = s.copy()
changed.iloc[k] += 1000 # perturb the value at position k
new = feature_fn(changed)
same = np.allclose(base.iloc[:k + 1].fillna(0), new.iloc[:k + 1].fillna(0))
return not same
print('rolling, no shift ', leaks(lambda x: x.rolling(7).mean(), s))
print('rolling, centered ', leaks(lambda x: x.rolling(7, center=True).mean(), s))
print('shift(1) + rolling', leaks(lambda x: x.shift(1).rolling(7).mean(), s))
print('lag 7 ', leaks(lambda x: x.shift(7), s))The first two lines print True. The last two print False. Only the last two are safe to use.
Habits that prevent leakage
- Define every feature in terms of
shift(k)withk >= 1, or a calendar value known in advance. - Fit any preprocessing on the training rows only, then apply it to the test rows.
- Split by time, and add a
gapat least as large as your longest window or lag when you validate. - Run the perturbation test on your feature function whenever you change it.
- Ask for each external column: would I have this value when I issue the forecast?
Exercise
A colleague builds the feature df['roll_mean_7'] = s.rolling(7).mean() and predicts s at the same row. Why is this leakage, and what single change fixes it?
Show answer
The window at row t includes s[t], so the feature contains the target. Shift the series by one step before rolling: s.shift(1).rolling(7).mean(). Then the window covers only t-7 to t-1.