Sub topic 13
Tuning Hyperparameters Without Peeking at the Future
This chapter assumes you can build lag and rolling features, that you know why a chronological split is required, and that you have run TimeSeriesSplit as in the previous chapter on validation. It also assumes you can fit a HistGradientBoostingRegressor. Here the question is how to choose its settings without leaking information from the future into your choices.
Why tuning can leak
Tuning means trying many hyperparameter settings and keeping the one with the best validation score. Each trial is a small experiment on your validation data. If you run enough trials, some setting will look good by chance. The score you report for that winner is optimistic, because you picked it for being the best on that very data.
Time series add a second risk. Any shuffled or random cross-validation lets the model train on rows from after the validation rows. The tuning then rewards settings that exploit future information, and those settings do not hold up in production.
Two rules keep tuning honest:
- Every validation block must come after its training block in time.
- The final test block must stay untouched until all choices are made.
A three-part layout
Split the history chronologically into three parts.
| Part | Used for | Touched how often |
|---|---|---|
| Training window | Fitting models | Every trial |
| Validation blocks (walk-forward) | Comparing settings | Every trial |
| Final test block | One last score | Once |
The tuning data is everything before the test block. You run walk-forward validation inside that region. After you pick the best settings, you refit on all of the tuning data and score once on the test block.
Which settings matter
For gradient boosting on lag features, a small set of hyperparameters does most of the work.
| Hyperparameter | Effect | Typical range |
|---|---|---|
| `learning_rate` | Step size of each tree. Smaller needs more trees. | 0.02 to 0.2 |
| `max_iter` | Number of boosting rounds (trees). | 100 to 1000 |
| `max_depth` / `max_leaf_nodes` | Complexity of each tree. | 3 to 8 / 15 to 63 |
| `min_samples_leaf` | Smallest leaf size. Larger values smooth the model. | 20 to 200 |
| `l2_regularization` | Penalty on leaf values. | 0 to 10 |
Time series tables are usually small, often only a few hundred or a few thousand rows. Overfitting is the main risk, so lean toward shallow trees, a larger min_samples_leaf, and a modest learning rate.
Feature choices such as which lags to include are also hyperparameters. Treat them the same way: compare them inside the same walk-forward folds.
A small grid search with walk-forward folds
Scikit-learn's GridSearchCV accepts a TimeSeriesSplit object as cv, so you can use it directly. The example below creates a synthetic daily series so it runs as shown. It holds out the last 20% as the final test block and tunes only on the rest.
import numpy as np
import pandas as pd
from sklearn.ensemble import HistGradientBoostingRegressor
from sklearn.metrics import mean_absolute_error
from sklearn.model_selection import GridSearchCV, TimeSeriesSplit
def make_features(s: pd.Series) -> pd.DataFrame:
df = pd.DataFrame({'y': s})
for lag in (1, 7, 14):
df[f'lag_{lag}'] = s.shift(lag)
past = s.shift(1)
df['roll_mean_7'] = past.rolling(7).mean()
df['roll_std_7'] = past.rolling(7).std()
df['dayofweek'] = s.index.dayofweek
return df.dropna()
# Synthetic daily series: weekly pattern plus noise
rng = np.random.default_rng(0)
idx = pd.date_range('2023-01-01', periods=900, freq='D')
series = pd.Series(
100 + 10 * np.sin(2 * np.pi * idx.dayofweek / 7) + rng.normal(0, 3, len(idx)),
index=idx,
)
data = make_features(series)
feature_cols = [c for c in data.columns if c != 'y']
cut = int(len(data) * 0.8)
tuning, final_test = data.iloc[:cut], data.iloc[cut:]
param_grid = {
'learning_rate': [0.03, 0.1],
'max_depth': [3, 6],
'min_samples_leaf': [20, 80],
'max_iter': [200, 400],
}
tscv = TimeSeriesSplit(n_splits=5, test_size=30, gap=7)
search = GridSearchCV(
HistGradientBoostingRegressor(random_state=0),
param_grid,
cv=tscv,
scoring='neg_mean_absolute_error',
n_jobs=-1,
)
search.fit(tuning[feature_cols], tuning['y'])
print('best params ', search.best_params_)
print('cv MAE ', -search.best_score_)
# GridSearchCV refits the best model on all tuning rows by default.
pred = search.best_estimator_.predict(final_test[feature_cols])
print('final test MAE', mean_absolute_error(final_test['y'], pred))
print('naive MAE ', mean_absolute_error(final_test['y'], final_test['lag_1']))
print('seasonal naive', mean_absolute_error(final_test['y'], final_test['lag_7']))Three details in this code are easy to get wrong.
- The
gap=7leaves seven rows between each training block and its validation block. The gap should be at least as long as the longest window that reaches across the boundary. Here the lag-14 and 7-day rolling features are already computed in the table, so the gap mainly guards against the label of a late training row overlapping the first validation rows. A larger gap is a conservative choice. GridSearchCVis given onlytuning. The final test rows are never seen by the search.- The grid has 16 combinations and 5 folds, so the search fits 80 models plus one refit. Grids grow multiplicatively, so keep them small or use random search.
Random search for larger spaces
When you have more than three or four hyperparameters, RandomizedSearchCV samples settings instead of trying every combination. It takes the same cv argument.
from scipy.stats import loguniform, randint
from sklearn.model_selection import RandomizedSearchCV
param_dist = {
'learning_rate': loguniform(0.01, 0.3),
'max_depth': randint(3, 9),
'min_samples_leaf': randint(10, 150),
'l2_regularization': loguniform(1e-3, 10),
'max_iter': randint(100, 600),
}
rsearch = RandomizedSearchCV(
HistGradientBoostingRegressor(random_state=0),
param_dist,
n_iter=30,
cv=tscv,
scoring='neg_mean_absolute_error',
random_state=0,
n_jobs=-1,
)
rsearch.fit(tuning[feature_cols], tuning['y'])
print(rsearch.best_params_, -rsearch.best_score_)Sampling the learning rate on a log scale matters. A uniform draw between 0.01 and 0.3 would rarely produce values near 0.01.
Early stopping that respects time
max_iter is the setting people most often tune by hand. Early stopping chooses it automatically: training stops when the validation score stops improving.
HistGradientBoostingRegressor has built-in early stopping, but by default it holds out a random fraction of the training rows. That random hold-out mixes past and future rows, which is the leak this chapter is trying to avoid. For time series, do the hold-out yourself.
import numpy as np
from sklearn.ensemble import HistGradientBoostingRegressor
from sklearn.metrics import mean_absolute_error
# Reuses `tuning`, `feature_cols`, and `final_test` from the grid search example.
inner_cut = int(len(tuning) * 0.85)
fit_part, val_part = tuning.iloc[:inner_cut], tuning.iloc[inner_cut:]
best_iter, best_mae = None, np.inf
model = HistGradientBoostingRegressor(
learning_rate=0.05, max_depth=4, min_samples_leaf=40,
max_iter=1, warm_start=True, early_stopping=False, random_state=0,
)
patience, since_best = 20, 0
for n in range(1, 1001):
model.set_params(max_iter=n)
model.fit(fit_part[feature_cols], fit_part['y'])
mae = mean_absolute_error(val_part['y'], model.predict(val_part[feature_cols]))
if mae < best_mae - 1e-6:
best_mae, best_iter, since_best = mae, n, 0
else:
since_best += 1
if since_best >= patience:
break
print('chosen max_iter', best_iter, 'val MAE', best_mae)
final = HistGradientBoostingRegressor(
learning_rate=0.05, max_depth=4, min_samples_leaf=40,
max_iter=best_iter, random_state=0,
)
final.fit(tuning[feature_cols], tuning['y'])
print('final test MAE', mean_absolute_error(final_test['y'], final.predict(final_test[feature_cols])))With warm_start=True, each call to fit adds trees to the existing model instead of starting over, so the loop stays fast. The validation part is the last 15% of the tuning region, so it lies after the fitting part.
The chosen max_iter was selected using val_part, so val_part is no longer a clean estimate of error. That is acceptable, because the clean estimate comes from final_test.
Alternatively, pass early_stopping=True together with validation_fraction. Be aware that scikit-learn draws that fraction at random when the target is regression, so for time series the manual loop above is the safer option.
Common errors
- Tuning on the test block. If you look at the test score and then change settings, the test block has become part of validation. Decide the number of tuning rounds in advance, or reserve a fresh block.
- Random folds.
KFold(shuffle=True)or the default integercvin a search on a regressor can place future rows in training. Always pass a time-ordered splitter. - Refitting on a window that differs from the one you tested. If the folds used an expanding window, refit on all the tuning data. If you plan to retrain on a rolling window in production, validate with
max_train_sizeset inTimeSeriesSplit. - Averaging hides instability. A mean MAE of 4.0 can come from folds scoring 3.0 and 5.0. Inspect
search.cv_results_for the per-fold scores and the standard deviation, and prefer settings that are consistent. - Chasing small gains. If two settings differ by less than the fold-to-fold spread, they are effectively tied. Pick the simpler one, for example fewer trees or shallower depth.
- Ignoring baselines. A tuned model that does not beat seasonal naive on the final test block is not worth deploying, however good the cross-validation score looks.
Summary of the workflow
- Reserve the final test block at the end of the history.
- Choose a walk-forward splitter with a gap that covers the feature horizon.
- Search a small, sensible space with
GridSearchCVorRandomizedSearchCV. - Set the number of trees with a chronological early-stopping hold-out.
- Refit on all tuning rows, then score once on the test block and compare with the naive and seasonal-naive baselines.
Exercise
A colleague tunes a gradient boosting model with GridSearchCV(model, grid, cv=5) on a lag-feature table and reports a cross-validated MAE of 2.1. In production the error is 3.4. Give two likely causes tied to this chapter, and say how to fix each.
Show answer
First, cv=5 for a regressor uses unshuffled K-fold, so most training sets include rows from after the validation fold. The model effectively sees the future, and the score is too optimistic. Fix it by passing TimeSeriesSplit (with a gap) as cv. Second, there may be no untouched final test block, so the 2.1 is the best score among many trials and is biased low. Fix it by holding out the last part of the history, tuning only on earlier rows, and scoring the chosen model on the held-out block once. Rolling features that include the current value could also leak, but the question points at the tuning procedure.
Exercise
Why is HistGradientBoostingRegressor(early_stopping=True) risky on a time series, and what does the chapter recommend instead?
Show answer
Its internal validation set is a random fraction of the training rows, so validation rows can come from before and after the training rows. This mixes past and future and can give a misleading stopping point. Instead, hold out the last part of the tuning region in time, grow the model with warm_start=True, stop when the chronological hold-out MAE has not improved for a set number of rounds, and refit with the chosen max_iter.
Exercise
A random search returns settings with a mean fold MAE of 3.90. Another setting has 3.95 with a much smaller spread across folds and a shallower model. Which would you pick and why?
Show answer
Pick the second setting. The 0.05 difference is smaller than the fold-to-fold variation, so the two are effectively tied on accuracy. The shallower, more stable model is less likely to be overfitted to the validation blocks and is simpler to maintain.