Sub topic 9
Fitting a Gradient Boosting Regressor
This chapter assumes you can build a lag and rolling-window feature table (the previous chapters), you know how a decision tree splits data, and you are comfortable with scikit-learn's fit and predict. We now fit a model on that table and check it against the baselines.
Why gradient boosting suits lag-feature tables
Once a series is turned into rows of lags, rolling statistics and calendar fields, each row is an ordinary tabular example. Gradient boosting works well on such tables for three reasons:
- It handles mixed feature types (counts, means, day of week) without scaling.
- It captures non-linear effects and interactions, such as "lag 7 matters more on weekends".
- It is fast and needs little tuning to give a reasonable first result.
Gradient boosting builds an ensemble of shallow decision trees one after another. Each new tree is fitted to the errors (more precisely, the negative gradient of the loss) of the ensemble so far. The final prediction is the sum of an initial constant and all trees' outputs, each scaled by a learning rate.
Choosing an implementation
scikit-learn offers two gradient boosting regressors. GradientBoostingRegressor is the classic version. HistGradientBoostingRegressor bins each feature into at most 255 buckets before searching for splits, which makes it much faster on tables with thousands of rows or more. It also handles missing values natively. LightGBM, XGBoost and CatBoost follow the same idea with more options.
| Model | Speed on large tables | Missing values | Notes |
|---|---|---|---|
| `GradientBoostingRegressor` | Slow | Not supported | Exact splits, many loss options |
| `HistGradientBoostingRegressor` | Fast | Supported | Built-in early stopping option |
| LightGBM / XGBoost | Fast | Supported | Extra install, more parameters |
This chapter uses HistGradientBoostingRegressor so the examples need only scikit-learn.
Fitting the model
The code below uses the make_features function from the lag-feature chapters. It splits chronologically, trains on the first 80% of rows, and compares the model with two baselines on the same test rows. To make the example run as shown, it first creates a synthetic daily series with a weekly pattern.
import numpy as np
import pandas as pd
from sklearn.ensemble import HistGradientBoostingRegressor
from sklearn.metrics import mean_absolute_error
def make_features(s: pd.Series) -> pd.DataFrame:
# s must have a DatetimeIndex with a regular frequency
df = pd.DataFrame({'y': s})
for lag in (1, 7, 14):
df[f'lag_{lag}'] = s.shift(lag)
past = s.shift(1) # exclude the current value from the window
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 cycle plus noise, no trend
rng = np.random.default_rng(0)
idx = pd.date_range('2023-01-01', periods=600, freq='D')
weekly = np.array([100, 110, 120, 125, 130, 160, 150])
series = pd.Series(weekly[idx.dayofweek] + rng.normal(0, 5, 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)
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']))Three details matter here:
- The split is by position, not random. Every test row is later in time than every training row.
- The baselines use the
lag_1andlag_7columns of the test rows, so all three scores cover exactly the same targets. random_state=0makes runs repeatable. It only affects behaviour when subsampling or early stopping with a validation fraction is active, but fixing it is a good habit.
On this synthetic data the model should beat the naive forecast clearly, because the weekly cycle makes yesterday a poor guide. It should come close to the seasonal naive score, which already captures the cycle. The noise limits how far any model can improve. If your model does not beat seasonal naive on real data, that is useful information: the features may add nothing beyond the seasonal pattern.
The parameters that matter
learning_ratescales each tree's contribution. Smaller values need more iterations but usually generalise better. Values from 0.03 to 0.1 are common starting points.max_iteris the number of trees. It trades off against the learning rate.max_depth,max_leaf_nodesandmin_samples_leafcontrol tree complexity. The defaultmax_leaf_nodes=31is generous for small tables. Raisingmin_samples_leafis a good first step against overfitting.l2_regularizationshrinks leaf values.lossdefaults to'squared_error'. Use'absolute_error'if you score with MAE and have outliers, or'quantile'for intervals (a later chapter).
Choosing these values properly needs time-aware validation, which is covered in a later chapter. For now, do not tune them against the test rows. Doing so turns the test score into an optimistic estimate.
Early stopping and time order
HistGradientBoostingRegressor can stop adding trees when a validation score stops improving. By default, early_stopping='auto' turns this on only when the training set has more than 10,000 rows. The validation rows are then taken by random sampling from the training data, not from its end.
Reading the result
Compare the three MAE values:
- If the model is no better than seasonal naive, the extra complexity is not paying off.
- If the model is much better on the test split but poor under walk-forward validation, suspect a split that was too lucky. One test block is a single sample of the future.
- If training error is far below test error, reduce complexity or add regularization.
You can check the first and last cases quickly by also computing the error on the training rows.
train_pred = model.predict(train[feature_cols])
print('train MAE ', mean_absolute_error(train['y'], train_pred))A training MAE much smaller than the test MAE signals overfitting. Some gap is normal.
Common errors
- Fitting on a shuffled table. Row order does not matter to the model, but shuffling before splitting does matter. Always split first by time.
- Passing the target column
yamong the features. This produces near-zero error and is easy to miss. Buildfeature_colsby excludingy, as above. - Predicting with columns in a different order than at fit time. Use the same
feature_colslist in both calls. - Expecting the model to extrapolate. A tree ensemble predicts values within the range seen in training. A rising series will be underpredicted, which the next chapter addresses.
Exercise
You fit a HistGradientBoostingRegressor on lag features. Its test MAE is 8.0, naive MAE is 20.0 and seasonal naive MAE is 7.9. Is the model worth deploying, and what is one check you would do next?
Show answer
Not on this evidence. The model beats naive but not seasonal naive, so it adds nothing beyond the weekly pattern that a simple rule already captures. The next check is walk-forward validation across several blocks, to see whether the model beats seasonal naive on average or in some periods. It would also be worth trying features or settings that could add information, and comparing again.
Exercise
A series has 50,000 training rows and you use the default early_stopping setting. Why might the reported validation score be misleading, and how do you avoid it?
Show answer
With more than 10,000 rows, 'auto' enables early stopping, and the validation rows are a random sample of the training data. Those rows are neighbours of training rows in time, so the score is optimistic and the chosen number of iterations may be too high. Set earlystopping=False and pick maxiter using a chronological hold-out or walk-forward validation.