Sub topic 11
Validating with chronological and walk-forward splits
This chapter assumes you can build lag and rolling features (earlier chapters), fit a scikit-learn regressor, and use pandas with a DatetimeIndex.
Why random splits fail
A random train/test split puts rows from the future into the training set. With lag features, a test row at day 100 has neighbours at days 99 and 101 in training. The model has effectively seen the answer. The score looks excellent and tells you nothing about real forecasting.
A valid split follows one rule: every training row comes before every validation row in time.
The chronological split
The simplest valid split cuts the table once. Train on the first 80%, test on the last 20%. This is the split used in the previous chapter's model-versus-baseline comparison.
Its weakness is that you get one score from one period. If that period is unusual (a holiday season, a level shift), the score misleads you.
Walk-forward validation
Walk-forward validation repeats the chronological split several times. Each fold trains on the past and validates on the block after it. Later folds train on more data.
scikit-learn provides this as TimeSeriesSplit.
from sklearn.model_selection import TimeSeriesSplit
tscv = TimeSeriesSplit(n_splits=5, test_size=30, gap=7)
scores = []
for train_idx, val_idx in tscv.split(data):
tr, va = data.iloc[train_idx], data.iloc[val_idx]
m = HistGradientBoostingRegressor(max_iter=300, learning_rate=0.05, random_state=0)
m.fit(tr[feature_cols], tr['y'])
scores.append(mean_absolute_error(va['y'], m.predict(va[feature_cols])))
print(scores)This code reuses data and feature_cols from the feature-building step, plus the imports from the model-fitting step.
The gap parameter
gap=7 removes seven rows between training and validation. Features such as lag_7 and rolling windows in the first validation rows are computed from values that sit near the end of the training block. The gap keeps that overlap small. Set it to at least your largest lag when you want a strict separation. It also mimics a real deployment, where the newest data is often not yet available when you forecast.
Reading the scores
Look at the spread of the fold scores, not only the mean. A large spread means the model is unstable across periods. Compare each fold against the naive and seasonal-naive MAE on the same rows. A model that beats the baselines on average but loses on some folds needs investigation.
Common errors
- Using
KFold(shuffle=True)ortrain_test_splitwith the default shuffle on time-ordered data. - Fitting scalers, encoders or target statistics on the full table before splitting.
- Building features after the split, which makes lags at the start of the validation block empty or wrong.
- Tuning hyperparameters on the same final test block you report. Keep a last block untouched.
- Reporting a single fold as if it represented the whole series.
Exercise
You build features with a maximum lag of 14 and use TimeSeriesSplit with gap=0. Why might the validation scores be slightly optimistic, and what change fixes it?
Show answer
With no gap, the first validation rows have lag features built from values at the end of the training block, and the model was fit on rows that sit right next to them. Information leaks across the boundary. Setting gap to at least 14 (the largest lag) separates the blocks so no validation feature overlaps with training targets.