Sub topic 16
One model for many series
This chapter assumes you have read the earlier chapters on lag features, rolling-window features and gradient boosting. It also assumes you know pandas groupby.
Local and global models
A local model is fitted to one series. If you have 500 products, you train 500 models. A global model is fitted once on the rows of all series stacked together. It learns patterns the series share, such as a weekly cycle or the response to a holiday.
A global model has three practical advantages:
- Short or new series borrow strength from long ones.
- You maintain one pipeline instead of hundreds.
- A gradient boosting model has enough rows to use more trees without overfitting.
A global model is weaker when series behave very differently. In that case, add an identifier feature or fit one model per group of similar series.
Building the stacked table
The main rule is that every lag and rolling feature must be computed inside each series. A plain shift on the stacked table would pull the last rows of series A into the first rows of series B.
import numpy as np
import pandas as pd
from sklearn.ensemble import HistGradientBoostingRegressor
from sklearn.metrics import mean_absolute_error
# Synthetic panel: three series with different levels
rng = np.random.default_rng(0)
dates = pd.date_range('2024-01-01', periods=200, freq='D')
frames = []
for sid, level in enumerate((10, 50, 200)):
weekly = 1 + 0.2 * np.sin(2 * np.pi * dates.dayofweek / 7)
y = level * weekly + rng.normal(0, level * 0.03, len(dates))
frames.append(pd.DataFrame({'series_id': f's{sid}', 'date': dates, 'y': y}))
panel = pd.concat(frames, ignore_index=True)
def make_panel_features(df: pd.DataFrame) -> pd.DataFrame:
df = df.sort_values(['series_id', 'date']).reset_index(drop=True)
g = df.groupby('series_id')['y']
for lag in (1, 7, 14):
df[f'lag_{lag}'] = g.shift(lag)
df['roll_mean_7'] = g.transform(lambda s: s.shift(1).rolling(7).mean())
df['dayofweek'] = df['date'].dt.dayofweek
df['series_code'] = df['series_id'].astype('category').cat.codes
return df.dropna()
data = make_panel_features(panel)
feature_cols = ['lag_1', 'lag_7', 'lag_14', 'roll_mean_7', 'dayofweek', 'series_code']
# Split by date so every series is cut at the same moment
all_dates = np.sort(data['date'].unique())
cutoff = all_dates[int(len(all_dates) * 0.8)]
train, test = data[data['date'] < cutoff], data[data['date'] >= cutoff]
is_cat = [c == 'series_code' for c in feature_cols]
model = HistGradientBoostingRegressor(
max_iter=300, learning_rate=0.05, categorical_features=is_cat, random_state=0
)
model.fit(train[feature_cols], train['y'])
test = test.assign(pred=model.predict(test[feature_cols]))
for sid, part in test.groupby('series_id'):
print(sid, 'model', mean_absolute_error(part['y'], part['pred']),
'seasonal naive', mean_absolute_error(part['y'], part['lag_7']))The code passes series_code as a categorical feature, so the trees can split on series identity.
Common errors
- Random or per-series row splits. Split on a single calendar cutoff, as above. Otherwise one series' future leaks into training while another is still being predicted.
- Mixed scales. MAE is dominated by the largest series. Report MAE per series, or use MASE to compare them.
- Level differences. A series with level 200 and one with level 10 force the trees to learn two ranges. Dividing each series by its training-period mean, then multiplying predictions back, often helps. Compute that mean from training rows only.
- Unequal history. Series that start later lose rows after
dropna. Check how many rows each series keeps.
Exercise
Why does the code compute g.shift(lag) on a grouped column instead of data['y'].shift(lag) on the whole stacked table?
Show answer
A plain shift ignores series boundaries. The first rows of each series would receive the last values of the previous series as their lags, which is wrong data. Grouping by series_id makes the first rows of each series NaN, and dropna removes them.