Sub topic 7
Temporal Leakage and Time-Aware Splits
This chapter assumes you know how to split data into train and test sets and how to use scikit-learn estimators and pipelines. It also assumes you have seen why preprocessing must be fit on training rows only.
What temporal leakage is
Temporal leakage happens when a model trains on information from a time later than the moment it is meant to predict. The model then looks better in evaluation than it can ever be in production, where the future is not available.
A random split causes this whenever rows are ordered in time. Say you predict next week's demand. A random split puts rows from March in the test set and rows from April and May in the training set. The model learns patterns from after the test period, such as a trend, a holiday effect, or a one-off event. It is then scored on the earlier period it effectively already saw.
Real deployment always runs forward. You train on the past and predict the future. Your evaluation should copy that order.
Why random splits fail on time-ordered data
Rows close in time are usually similar. Neighbouring days share weather, prices, and customer behaviour. With a random split, almost every test row has near-identical neighbours in the training set. The model can score well by interpolating between them, which is much easier than forecasting.
Two other problems appear:
- Trend leakage. If the target drifts upward over time, the model sees the later part of the trend during training.
- Feature leakage through time. Rolling averages, lag features, and scaling statistics computed over the whole dataset can include future values.
Split by time
The simplest fix is a single cut. Sort by time, train on everything before a cutoff, and test on everything after it.
For cross-validation, use TimeSeriesSplit. It builds several folds, and each test fold comes after its training rows. The training window grows with each fold.
import numpy as np
from sklearn.model_selection import TimeSeriesSplit
X = np.arange(12).reshape(-1, 1) # rows ordered by time
for train_idx, test_idx in TimeSeriesSplit(n_splits=3).split(X):
assert train_idx.max() < test_idx.min()
print(train_idx, test_idx)The assert checks the property that matters: every training index is smaller than every test index. TimeSeriesSplit does not sort your data. It assumes the rows are already in time order, so sort first.
Other places time leaks in
A correct split does not protect you if the features were built carelessly. Check these:
- Lag and rolling features. A rolling mean at time
tmust use only rows up tot-1, not a window centred ont. Compute features from the past only, such as a shifted series. - Whole-dataset statistics. Means, scalers, and encoders must be fit on the training window only, as in the preprocessing chapter.
- Labels that are known late. A churn label may only be confirmed 30 days after the event. Training rows whose labels would not yet be known at the cutoff should be excluded.
- Overlapping targets. If the target covers a window, such as the next 7 days' sales, a training row just before the cutoff has a target that overlaps the test period. Leave a gap between the training and test sets.
TimeSeriesSplit supports a gap through its gap parameter.
import numpy as np
from sklearn.model_selection import TimeSeriesSplit
X = np.arange(20).reshape(-1, 1)
for train_idx, test_idx in TimeSeriesSplit(n_splits=3, gap=2).split(X):
print(train_idx.max(), test_idx.min())With gap=2, two rows are skipped between the end of each training set and the start of its test set.
Time-aware splits and tuning
Hyperparameter search must also respect time. Pass a time-aware splitter to GridSearchCV as cv. Keep a final test period after the last tuning period, and do not use it until the end.
import numpy as np
from sklearn.linear_model import Ridge
from sklearn.model_selection import GridSearchCV, TimeSeriesSplit
rng = np.random.default_rng(0)
X = rng.normal(size=(200, 3))
y = X @ [1.0, 2.0, 0.5] + rng.normal(size=200)
search = GridSearchCV(
Ridge(), {"alpha": [0.1, 1, 10]}, cv=TimeSeriesSplit(n_splits=4)
)
search.fit(X[:150], y[:150]) # tuning window
print(search.score(X[150:], y[150:])) # later, untouched periodWhen time is not enough
Time order is one kind of dependence. Data can also be dependent through groups, such as several rows per customer. If the same customer appears before and after the cutoff, a time split can still leak. The next chapter covers group and duplicate leakage.
Exercise
A colleague predicts the next 7 days' sales for each row and uses TimeSeriesSplit with no gap. Scores look better than production results. What leak could remain, and how do you reduce it?
Show answer
Each training row's target covers the following 7 days, so the last training rows have targets that overlap the start of the test fold. The model has effectively seen part of the test period. Set gap=7 (or more) in TimeSeriesSplit so the training window ends at least 7 rows before the test window starts. Also check that lag and rolling features use only past values.