Sub topic 10
Why trees struggle with trend, and how to work around it
This chapter assumes you can build lag and rolling features, fit a HistGradientBoostingRegressor, and split data chronologically. It explains one failure that these tools hide: a tree model cannot predict values outside the range it saw in training. It then shows three ways to deal with that.
Why trees cannot extrapolate
A regression tree sends each row to a leaf. The leaf predicts the average target of the training rows that landed there. Gradient boosting adds many such trees together. The sum of leaf averages can never be larger than the training targets allow, apart from small overshoots from the boosting steps.
Suppose a series climbs steadily. In training the highest value is 200. In the test period the true values reach 240. Every test row with a large lag_1 falls into the same rightmost leaves as the largest training rows. The model predicts roughly 200 and stays flat while the data keeps rising.
A linear model does not have this problem, because its prediction grows with the input. A tree model has no such slope.
The failure is easy to miss for three reasons:
- Random train/test splits mix old and new rows, so every test value lies inside the training range.
- Cross-validation folds early in the series see little trend.
- The error grows gradually, so the first few test steps look fine.
What counts as a trend problem
Two cases cause trouble:
- A steady trend, where the level keeps rising or falling.
- A level shift, where the level jumps once, for example after a price change or a new store opening.
Seasonality alone is not a problem. Seasonal values repeat, so they stay inside the training range.
Features are affected as well as targets. If lag_1 or roll_mean_7 reach values never seen in training, the splits cannot use them, and those rows get treated like the highest training rows.
Workaround 1: predict the change, not the level
Differencing replaces the target y with y - lag_1. A series with a steady trend has a roughly constant difference, so the target stays inside the training range. You add lag_1 back after predicting.
The features need the same treatment. Express each one relative to lag_1, for example lag_7 - lag_1. Drop the raw level features.
Workaround 2: remove a fitted trend
Fit a simple trend, such as a straight line over time, on the training period only. Subtract it, model the residuals with trees, and add the trend back to the predictions. The line supplies the extrapolation and the trees supply the seasonal structure and interactions.
Comparing the three on synthetic data
The series below has a slope of 0.3 per day, a weekly cycle and noise. The script compares a raw-level model, a differenced model, a detrended model and the seasonal-naive baseline on the last 20% of rows.
import numpy as np
import pandas as pd
from sklearn.ensemble import HistGradientBoostingRegressor
from sklearn.linear_model import LinearRegression
from sklearn.metrics import mean_absolute_error
rng = np.random.default_rng(0)
n = 600
t = np.arange(n)
idx = pd.date_range("2022-01-01", periods=n, freq="D")
s = pd.Series(50 + 0.3 * t + 8 * np.sin(2 * np.pi * t / 7)
+ rng.normal(0, 2, n), index=idx)
def make_features(s):
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["dayofweek"] = s.index.dayofweek
return df.dropna()
def fit_predict(X_tr, y_tr, X_te):
m = HistGradientBoostingRegressor(max_iter=300, learning_rate=0.05,
random_state=0)
return m.fit(X_tr, y_tr).predict(X_te)
data = make_features(s)
cut = int(len(data) * 0.8)
train, test = data.iloc[:cut], data.iloc[cut:]
cols = [c for c in data.columns if c != "y"]
# A: raw levels
pred_a = fit_predict(train[cols], train["y"], test[cols])
# B: differenced target and features relative to lag_1
X = data[["dayofweek"]].copy()
for c in ("lag_7", "lag_14", "roll_mean_7"):
X[c + "_rel"] = data[c] - data["lag_1"]
d = data["y"] - data["lag_1"]
pred_b = fit_predict(X.iloc[:cut], d.iloc[:cut], X.iloc[cut:]) + test["lag_1"]
# C: linear trend fitted on training rows only, trees on the residuals
pos = s.index.get_indexer(data.index[:cut])
lin = LinearRegression().fit(pos.reshape(-1, 1), s.iloc[pos])
trend = pd.Series(lin.predict(t.reshape(-1, 1)), index=s.index)
rd = make_features(s - trend)
pred_c = (fit_predict(rd[cols].iloc[:cut], rd["y"].iloc[:cut],
rd[cols].iloc[cut:])
+ trend.loc[test.index].to_numpy())
for name, p in [("raw levels", pred_a), ("differenced", pred_b),
("detrended", pred_c)]:
print(f"{name:12s} MAE", round(mean_absolute_error(test["y"], p), 2))
print("seasonal naive MAE",
round(mean_absolute_error(test["y"], test["lag_7"]), 2))On this series the raw-level model has a much larger error than the other three, because its predictions stop near the training maximum while the test values keep rising. The exact numbers depend on the library version. Check that the gap is large before you trust the setup.
The trend fit uses only rows before cut. Fitting the line on the full series would leak future information into the model, which is the look-ahead bias covered earlier in this tutorial.
Choosing a remedy
The trade-offs are:
| Approach | Strength | Weakness |
|---|---|---|
| Differencing | Handles level shifts and changing slopes | Errors accumulate in multi-step forecasts, and noise in `lag_1` carries into every prediction |
| Linear detrend | Keeps a clean level forecast and extrapolates smoothly | A wrong slope grows with the horizon, and a level shift breaks it |
| Linear leaves (LightGBM `linear_tree=True`) | Fits a local slope in each leaf | Extrapolation can become unstable far from the training data |
Interaction with multi-step forecasting
Both workarounds need care in the recursive loop. With differencing, each step predicts a change. You add it to the latest value, whether observed or predicted, and recompute the relative features from the extended history. With detrending, compute the trend for each future timestamp. Add it back to each prediction, and subtract it again before you store the prediction as a lag.
Predictions fed back as lags are the model's own output. A small bias in the predicted change adds up step after step.
Common mistakes
- Fitting the trend or computing differencing statistics on the full series instead of the training rows.
- Differencing the target but leaving raw level features in the table, so the features still go out of range.
- Forgetting to add the trend or
lag_1back before scoring, which produces absurdly low or high errors. - Over-differencing a series that has no trend, which adds noise.
- Using a straight line on a series that flattens or bends. In that case use differencing instead.
Exercise
A gradient boosting model trained on raw lag features forecasts daily sales. Sales grew steadily for two years, and the model's forecasts for month 25 sit flat at about the maximum of the training data. Explain why, and name two fixes.
Show answer
Each leaf predicts an average of training targets, so the model's output stays within the range it saw in training. Test rows with unusually high lags fall into the same top leaves as the highest training rows, which gives a flat forecast. Two fixes are to difference the target (predict y - lag_1, with features relative to lag_1, then add lag_1 back) and to fit a linear trend on the training data only, model the residuals with trees, and add the trend back.