Sub topic 9
Time-ordered data: forward-chaining splits
This chapter assumes you know k-fold cross-validation, how to wrap preprocessing in a scikit-learn pipeline, and the idea of data leakage. Here you will learn why ordinary k-fold fails on data ordered in time, and how forward-chaining splits fix it.
Why shuffled k-fold breaks on time series
Ordinary k-fold, especially with shuffle=True, mixes past and future rows. A model can then train on Friday and Sunday and be tested on Saturday. In production it never has that luxury, because it only sees the past when it predicts the future.
Neighbouring rows in a time series are also correlated. If Saturday's row is in the test set, Friday's near-copy is in the training set. This leaks information, and the scores come out too optimistic.
The rule is that every test row must come later in time than every training row. Your data must also be sorted by time first.
How forward-chaining works
TimeSeriesSplit cuts the series into consecutive blocks. Fold 1 trains on the first block and tests on the second. Each later fold adds the previous test block to the training set and tests on the next block.
You can print the indices to check:
import numpy as np
from sklearn.model_selection import TimeSeriesSplit
X = np.arange(12).reshape(6, 2)
for train_idx, test_idx in TimeSeriesSplit(n_splits=3).split(X):
print("train:", train_idx, "test:", test_idx)This prints:
train: [0 1 2] test: [3]
train: [0 1 2 3] test: [4]
train: [0 1 2 3 4] test: [5]Two properties differ from k-fold:
- The test sets do not cover all the data. The earliest rows are only ever used for training.
- The training sets have different sizes. Early folds train on little data, so their scores are usually worse and noisier.
Using it with `cross_val_score`
You pass TimeSeriesSplit as the cv argument, just like StratifiedKFold. The gap argument skips rows between the training and test windows. Use it when the target looks ahead, for example when it is a 3-day-ahead value. Without a gap, the last training labels overlap the first test period.
import numpy as np
from sklearn.linear_model import Ridge
from sklearn.model_selection import TimeSeriesSplit, cross_val_score
rng = np.random.default_rng(0)
t = np.arange(200)
X = t.reshape(-1, 1)
y = 0.05 * t + rng.normal(size=200)
cv = TimeSeriesSplit(n_splits=5, gap=3)
scores = cross_val_score(Ridge(), X, y, cv=cv,
scoring="neg_mean_absolute_error")
print(-scores)
print(f"mean MAE={-scores.mean():.3f}")The scorer is negated because scikit-learn treats higher scores as better, so error metrics come back as negative numbers.
Other useful parameters:
| Parameter | Effect |
|---|---|
| `n_splits` | Number of train/test pairs |
| `test_size` | Fixed number of rows in each test window |
| `gap` | Rows dropped between train and test |
| `max_train_size` | Caps the training window, giving a rolling window instead of an expanding one |
Use max_train_size when old data is no longer representative, for example after the process has changed.
Common mistakes
- Using random k-fold on time series because it gives a better-looking score.
- Forgetting
gapwhen the target or the features use a rolling window. - Averaging fold scores without checking the trend. If early folds are much worse, the model may just need more history.
- Assuming forward-chaining covers other dependence. If one series has several entities, such as stores or patients, you may also need grouping.
Exercise
A model predicts next week's sales from the previous four weeks. You build features with a 4-week rolling mean and evaluate with TimeSeriesSplit(n_splits=5). Why might the scores still be optimistic, and what argument helps?
Show answer
Rolling features and the target overlap in time, so the last training rows share information with the first test rows. Setting gap to at least the window length (here 4 rows if rows are weekly) removes that overlap.