Sub topic 10
Why Trees Struggle with Trend, and How to Work Around It
This chapter assumes you can build lag features, fit a HistGradientBoostingRegressor, and split data chronologically. It covers one failure mode of tree models on trending series and two fixes.
The extrapolation limit
A decision tree predicts by averaging the training targets in a leaf. A boosted ensemble sums many such trees. Every prediction is therefore built from values the model saw during training. It cannot output a number far above the largest training target.
Suppose a series climbs steadily. The test period holds values higher than anything in training. The model's forecast flattens near the top of the training range, while the real series keeps rising. The error grows with every step.
import numpy as np
import pandas as pd
from sklearn.ensemble import HistGradientBoostingRegressor
idx = pd.date_range("2024-01-01", periods=300, freq="D")
y = pd.Series(np.arange(300, dtype=float) + 5 * np.sin(np.arange(300) * 2 * np.pi / 7), index=idx)
df = pd.DataFrame({"y": y, "lag_1": y.shift(1), "lag_7": y.shift(7)}).dropna()
cut = int(len(df) * 0.8)
train, test = df.iloc[:cut], df.iloc[cut:]
cols = ["lag_1", "lag_7"]
m = HistGradientBoostingRegressor(random_state=0).fit(train[cols], train["y"])
pred = m.predict(test[cols])
print("train max:", train["y"].max())
print("pred max: ", pred.max())
print("test max: ", test["y"].max())The predictions stop near the training maximum while the test targets exceed it. Raw lag values are the cause: lag_1 in the test period is itself outside the range seen in training, and the trees treat all such values like the largest one they know.
Fix 1: model the change, not the level
Predict the difference from a recent value, then add that value back. Differences of a trending series stay in a stable range.
df["target_diff"] = df["y"] - df["lag_1"]
train, test = df.iloc[:cut], df.iloc[cut:]
m = HistGradientBoostingRegressor(random_state=0).fit(train[cols], train["target_diff"])
pred = test["lag_1"] + m.predict(test[cols])
print("max prediction:", pred.max())The forecast is now lag_1 plus a learned step, so it follows the series upward. In recursive forecasting, add each predicted difference to the last value before the next step.
You can also make the features stationary, for example by using lag_1 - lag_7 or ratios to a rolling mean instead of raw levels.
Fix 2: detrend first, then add the trend back
Fit a simple model such as linear regression on time, subtract it, and train the boosting model on the residuals. At forecast time, extrapolate the line and add the boosted residual forecast.
| Approach | Handles steady trend | Handles level shifts | Cost |
|---|---|---|---|
| Raw levels | No | No | None |
| Differenced target | Yes | Partly | Errors accumulate in recursive use |
| Linear detrend plus residual model | Yes | No, unless the line is refit | Assumes the trend continues |
Exercise
A boosted model trained on raw sales levels forecasts a flat line after sales hit a new record. Why does this happen, and what is one change that fixes it?
Show answer
Tree leaves average training targets, so predictions cannot go beyond the range seen in training. Train on the difference from the previous value (or on residuals after removing a fitted trend), then add that value or trend back to get a forecast on the original scale.