Sub topic 13
Tuning hyperparameters without peeking at the future
This chapter assumes you can build lag and rolling features, fit a HistGradientBoostingRegressor, and run TimeSeriesSplit as in earlier chapters. The code uses the data table and feature_cols list from those chapters.
Why ordinary tuning breaks
Tools like GridSearchCV(cv=5) or RandomizedSearchCV shuffle rows when the splitter is not chronological. A model tuned that way is scored on days that sit between its training days. It can look good on that score and still fail on genuinely future data.
Two more leaks are easy to miss:
- Hyperparameters chosen on the same data you report as the final score. Every candidate you try is another chance to fit noise in the validation block.
- Built-in early stopping. By default, scikit-learn's
early_stoppingholds out a random fraction of the training rows, so the stopping point is chosen on shuffled data.
A safe procedure
- Reserve the last block of the series as a test set. Do not touch it while tuning.
- Tune on the earlier "development" part with walk-forward splits, using
gapat least as large as your longest lag-feature reach that crosses the boundary. - Choose the number of boosting iterations from the validation blocks, not from random hold-out rows.
- Refit once on all development data with the chosen settings. Score once on the test block.
Example
staged_predict returns the predictions after each boosting iteration. That lets one fit per fold score every iteration count, which gives early stopping that respects time order.
import itertools
import numpy as np
from sklearn.ensemble import HistGradientBoostingRegressor
from sklearn.metrics import mean_absolute_error
from sklearn.model_selection import TimeSeriesSplit
cut = int(len(data) * 0.8)
dev, test = data.iloc[:cut], data.iloc[cut:]
grid = {
'learning_rate': [0.03, 0.1],
'max_depth': [3, 6],
'min_samples_leaf': [20, 50],
}
tscv = TimeSeriesSplit(n_splits=5, test_size=30, gap=7)
best = None
for lr, depth, leaf in itertools.product(*grid.values()):
curves = [] # one MAE-per-iteration curve per fold
for tr_idx, va_idx in tscv.split(dev):
tr, va = dev.iloc[tr_idx], dev.iloc[va_idx]
m = HistGradientBoostingRegressor(
learning_rate=lr, max_depth=depth, min_samples_leaf=leaf,
max_iter=500, early_stopping=False, random_state=0,
)
m.fit(tr[feature_cols], tr['y'])
curves.append([
mean_absolute_error(va['y'], p)
for p in m.staged_predict(va[feature_cols])
])
mean_curve = np.mean(curves, axis=0)
n_iter = int(mean_curve.argmin()) + 1
score = float(mean_curve.min())
if best is None or score < best['score']:
best = dict(score=score, lr=lr, depth=depth, leaf=leaf, n_iter=n_iter)
print('best settings:', best)
final = HistGradientBoostingRegressor(
learning_rate=best['lr'], max_depth=best['depth'],
min_samples_leaf=best['leaf'], max_iter=best['n_iter'],
early_stopping=False, random_state=0,
)
final.fit(dev[feature_cols], dev['y'])
print('test MAE', mean_absolute_error(test['y'], final.predict(test[feature_cols])))Practical notes
- Start with
learning_rate,max_depthandmin_samples_leaf. Time series are usually small and noisy, so shallow trees and larger leaves often generalize better. - Keep the grid small. A grid of 8 settings costs 40 fits here, and larger grids make the validation score less trustworthy.
- Compare the tuned test MAE with the seasonal-naive baseline. If tuning barely moves the score, the features matter more than the settings.
Exercise
Why is HistGradientBoostingRegressor(early_stopping=True) risky for forecasting, and what does the example use instead?
Show answer
Its internal validation split is a random fraction of the training rows, so the model is stopped using days that surround its training days, which leaks future information. The example sets early_stopping=False, scores staged_predict on later walk-forward validation blocks, and picks the iteration count with the lowest mean MAE.