Sub topic 9
Fitting a Gradient Boosting Regressor
This chapter assumes you can use pandas with a DatetimeIndex, know scikit-learn's fit/predict interface, and understand decision trees at a basic level. It also assumes you have built the lag, rolling and calendar features from the earlier chapters.
How gradient boosting works
Gradient boosting builds an ensemble of shallow decision trees one after another. The first tree predicts the target. Each later tree is trained on the errors the ensemble still makes, and its output is added with a small weight, the learning_rate. After many rounds, the sum of many weak trees gives a strong model.
Two settings control most of the behavior:
max_iteris the number of trees. More trees fit the training data more closely.learning_ratescales each tree's contribution. A smaller rate needs more trees but usually generalizes better.
For tabular features like lags, HistGradientBoostingRegressor is a good default. It bins feature values into histograms, so it trains quickly on large tables. It also accepts missing values natively.
Fitting the model
The split must be chronological. The model trains on the earliest 80% of rows and is tested on the latest 20%. Shuffling rows would let the model see the future during training.
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']))This code assumes series is a pd.Series with a regular DatetimeIndex and that make_features is defined as in the lag and window chapters. The lag_1 column is the naive forecast and lag_7 is the weekly seasonal-naive forecast. Both are computed on the same test rows as the model, so the three numbers are directly comparable.
Reading the result
If the model beats both baselines, the lag and calendar features carry signal that the simple rules miss. If it only matches the seasonal-naive baseline, the model has mostly learned "repeat last week". That is useful as a sanity check but gives you little reason to prefer the more complex model.
Common errors
- Too many trees on a small series. The model memorizes the training period. Training error falls while test error rises. The next chapters cover early stopping and time-aware tuning.
- Shuffled splits.
train_test_splitwith its default shuffling leaks future rows into training and makes the score look better than it will be in production. - Scoring on training rows. A low training MAE says little. Always report error on held-out later rows.
- Forgetting that trees cannot extrapolate. The model predicts averages of values seen in training. If the series trends beyond its training range, forecasts flatten. The trend chapter covers this.
Exercise
You lower learning_rate from 0.05 to 0.01 and keep max_iter=300. Test error gets worse. What is the most likely cause, and what would you change?
Show answer
Each tree now contributes less, so 300 trees are not enough and the model underfits. Raise max_iter (ideally with early stopping on a chronologically later validation block) so the smaller learning rate has enough rounds to converge.