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. The goal is a validation setup whose score predicts how the model will do on data it has not seen yet.
Why random splits fail on time series
A random train/test split, or ordinary k-fold cross-validation, shuffles rows. For tabular data with independent rows that is fine. For a forecasting table it breaks in two ways.
- Future rows train the model. If the model is fit on rows from March and scored on a row from February, it has learned from the future. In production, that never happens.
- Neighbouring rows overlap. Row t has
lag_1equal to the target of row t−1, and its rolling mean covers the previous seven targets. A test row's features are copies of training targets (and the reverse). The model gets credit for interpolating between known neighbours, which is easier than forecasting.
The result is an optimistic score that falls apart after deployment. The fix is to make every validation row come after every training row in time.
The single chronological split
The simplest valid scheme is to cut the table at a date. Everything before the cut is training data and everything after is test data.
from sklearn.ensemble import HistGradientBoostingRegressor
from sklearn.metrics import mean_absolute_error
data = make_features(series)
feature_cols = [c for c in data.columns if c != 'y']
cut = int(len(data) * 0.8)
train, test = data.iloc[:cut], data.iloc[cut:]
model = HistGradientBoostingRegressor(max_iter=300, learning_rate=0.05, random_state=0)
model.fit(train[feature_cols], train['y'])
pred = model.predict(test[feature_cols])
print('model MAE ', mean_absolute_error(test['y'], pred))
print('naive MAE ', mean_absolute_error(test['y'], test['lag_1']))
print('seasonal naive ', mean_absolute_error(test['y'], test['lag_7']))Always print the baselines next to the model on the same rows. A model MAE of 12 means nothing until you know the seasonal-naive MAE is 14 or 9.
This split is cheap and mirrors deployment, but it has weaknesses:
- It gives one number. If the last 20% of the series is unusual (a holiday season, a promotion, a level shift), you cannot tell whether the score is typical.
- It uses little of the data for evaluation, and the model never sees the most recent test rows during training.
Walk-forward validation
Walk-forward validation (also called rolling-origin or time-series cross-validation) repeats the chronological split several times. Each fold trains on the past and validates on a block that follows it. The training window grows, or slides, from fold to fold.
scikit-learn provides TimeSeriesSplit for this:
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)Key parameters:
| Parameter | Meaning | Effect |
|---|---|---|
| `n_splits` | Number of folds | More folds give a more stable estimate and cost more fits |
| `test_size` | Rows per validation block | Set it to your real forecast horizon, or a multiple of it |
| `gap` | Rows skipped between train and validation | Removes overlap between training targets and validation features |
| `max_train_size` | Cap on training rows | Turns the expanding window into a sliding window |
The folds are placed at the end of the series. With n_splits=5 and test_size=30, the validation blocks cover the last 150 rows, and the first fold's training set is everything before its block (minus the gap).
Choosing the gap
Features such as lag_14 and roll_mean_7 at validation row t read targets from rows t−14 to t−1. If training ends at t−1, those targets are in the training set. That is not leakage in the strict sense, because at forecast time you also know those values. But it matters in two cases.
- Multi-step forecasts. If you will forecast 7 days ahead, the features for day t+6 are not available at forecast origin t. A gap equal to the horizon makes validation mimic the delay between the last known value and the predicted period.
- Targets that overlap in time. If a target is itself an aggregate (a 7-day sum), neighbouring training and validation targets share underlying data. The gap should be at least as long as that window.
A practical rule: set gap to at least the forecast horizon minus one, and to at least the length of any window used to build the target.
Expanding versus sliding windows
- Expanding (the default) uses all past data. It suits stable processes and gives later folds more training data.
- Sliding (set
max_train_size) uses a fixed-length recent window. It suits series whose behaviour drifts, because old regimes stop influencing the model. It also keeps fold training costs equal.
If a sliding window scores better than an expanding one, the series has drifted. That is useful information for how you retrain in production.
Reading the fold scores
Do not only average the scores. Look at them.
import numpy as np
print('mean MAE', np.mean(scores))
print('std MAE', np.std(scores))
print('worst fold', int(np.argmax(scores)))- A high spread means performance depends on the period. Investigate the worst fold: a holiday, an outage, a level shift.
- Compute the baselines on the same folds and compare fold by fold. A model that wins on average but loses on two of five folds is less convincing than one that wins on all five.
- Folds are not independent, because their training sets overlap. Treat the standard deviation as a rough guide, not a confidence interval.
Preprocessing inside the loop
Anything fitted on data must be fitted on the training part of each fold only. Common offenders:
- Scalers or target encoders fitted on the full table before splitting.
- Feature selection done on the whole series.
- Hyperparameters chosen by looking at the final test block, then reported as the test score.
The feature table itself is safe to build once, as long as every feature uses only past values (shifted before rolling, as in make_features). Fitted transformations are not. Put them in a scikit-learn Pipeline and fit the pipeline inside each fold.
Keep a final holdout
If you use walk-forward scores to choose features or hyperparameters, those scores become optimistic, because you picked the best of many tries. Reserve the last block of the series, never touched during selection, and score on it once.
holdout_size = 60
dev, holdout = data.iloc[:-holdout_size], data.iloc[-holdout_size:]
# run TimeSeriesSplit and all tuning on `dev` only
# then refit on all of `dev` and score once on `holdout`When the final model is deployed, refit it on all available data, including the holdout.
Common mistakes
- Shuffling.
train_test_splitshuffles by default. If you must use it, passshuffle=False.KFold(shuffle=True)is never appropriate here. - Dropping the index order.
TimeSeriesSplitassumes rows are sorted by time. Sort first, and checkdata.index.is_monotonic_increasing. - Ignoring missing timestamps. If the series has gaps, row counts no longer equal time spans, so
gap=7may not mean seven days. Reindex to a regular frequency first. - A validation block shorter than the seasonal period. A 3-day block with weekly seasonality hides day-of-week errors. Use at least one full cycle.
- Comparing scores across different folds. Two models are comparable only when evaluated on identical splits.
Summary of the procedure
- Sort by time and make the frequency regular.
- Build features using only past values.
- Hold out the final block.
- Run walk-forward folds on the rest, with a gap and a test size matching your horizon.
- Report the model and baselines fold by fold.
- Score once on the holdout, then refit on everything for deployment.
Exercise
You forecast daily demand 7 days ahead using features up to lag 14. Your validation uses TimeSeriesSplit(n_splits=5, test_size=7) with no gap and gives an MAE well below the seasonal-naive baseline. Name one reason this score may be too optimistic and give the change you would make.
Show answer
With no gap, each validation block starts immediately after the training data, so validation features are built from values known right up to the block's first day. In production, a 7-day-ahead forecast made at origin t cannot use the values from t+1 to t+6 for the later days in the horizon. The validation setup therefore gives the model fresher information than it will have. Set gap=6 (horizon minus one) or evaluate with features restricted to what is known at the forecast origin, for example by using direct models or recursive forecasting inside each fold. Then compare against the baselines again.
Exercise
Walk-forward folds for a model give MAE values of 8, 9, 8, 10 and 31, while seasonal naive gives 12, 13, 12, 14 and 33. What does this tell you, and what would you do next?
Show answer
The model beats the baseline on every fold, but the last fold is much worse for both, so the period itself is hard (for example a holiday, outage or level shift) rather than the model being at fault. Inspect that period, check whether a trend or level shift occurred that trees cannot extrapolate, consider a sliding window or a detrending step, and report the mean together with the spread instead of the mean alone.