Sub topic 16
One model for many series
This chapter assumes you have read the earlier chapters of this tutorial. You should be comfortable building lag and rolling features, splitting data chronologically, and comparing a model against a seasonal-naive baseline. It also assumes you know pandas groupby and scikit-learn's fit/predict.
Local models and global models
So far you have fitted one model to one series. That is a local model. If you have 500 products, a local approach means 500 models to fit, tune, monitor and retrain.
A global model is a single model trained on the rows of all series at once. Lag features make this possible. After you turn each series into a table of lags, rolling statistics and calendar columns, every row has the same shape. A row from product A and a row from product B differ only in their values, so you can stack them into one table.
The main benefit is shared strength. A short or noisy series can borrow patterns, such as weekly shape or holiday response, from longer ones. Operations also get simpler. The cost is that the model must learn how series differ, and you must prepare the table more carefully.
Building the stacked table
The most common mistake is computing lags over the stacked table as if it were one series. The first rows of series B would then get lags from the end of series A. Every time-shifted feature must be computed within each series.
The code below builds three synthetic daily series with very different levels. It applies the same features as before, now grouped by series.
import numpy as np
import pandas as pd
from sklearn.ensemble import HistGradientBoostingRegressor
rng = np.random.default_rng(0)
dates = pd.date_range('2024-01-01', periods=300, freq='D')
weekly = np.array([0.8, 0.9, 1.0, 1.0, 1.1, 1.3, 0.9])
frames = []
for i, level in enumerate([10, 50, 200]):
noise = 1 + rng.normal(0, 0.05, len(dates))
y = level * weekly[dates.dayofweek] * noise
frames.append(pd.DataFrame({'series_id': f's{i}', 'date': dates, 'y': y}))
panel = pd.concat(frames, ignore_index=True)
def make_panel_features(panel: pd.DataFrame) -> pd.DataFrame:
panel = panel.sort_values(['series_id', 'date']).reset_index(drop=True)
g = panel.groupby('series_id')['y']
for lag in (1, 7, 14):
panel[f'lag_{lag}'] = g.shift(lag)
past = g.shift(1) # exclude the current value, within each series
past_by_series = past.groupby(panel['series_id'])
panel['roll_mean_7'] = past_by_series.transform(lambda x: x.rolling(7).mean())
panel['roll_std_7'] = past_by_series.transform(lambda x: x.rolling(7).std())
panel['dayofweek'] = panel['date'].dt.dayofweek
return panel.dropna()
data = make_panel_features(panel)
print(data.groupby('series_id').size())Each series loses its own first 15 rows to dropna. Series of different lengths are fine, because the table is just a list of rows.
Telling the model which series a row belongs to
A tree model can only specialise by series if it can see which series a row comes from. There are three common options:
- Add the series identifier as a categorical feature. This is the simplest option, and gradient boosting can split on it directly.
- Add descriptive attributes, such as product category, store region or price tier. These let the model generalise to a series it has never seen, which an identifier cannot do.
- Add nothing, and let the lag values alone identify the series. This works when levels differ a lot, but it is fragile.
An identifier lets the model memorise per-series quirks. Attributes let it transfer knowledge. With many series, attributes are usually the better choice, and you can include both.
Putting series on a common scale
Series with levels of 10 and 200 cause a second problem. A tree splits on absolute values, so it spends many splits just separating "small" series from "large" ones. Errors from large series also dominate the loss, so the model quietly neglects the small ones.
The standard fix is to divide each series by a scale, train on the scaled values, and multiply predictions back. A simple scale is the series mean over the training period. You must compute it from training rows only. A scale taken from the full history carries information about the test period.
cut_date = data['date'].max() - pd.Timedelta(days=60)
is_train = data['date'] <= cut_date
scale = data.loc[is_train].groupby('series_id')['y'].mean()
s = data['series_id'].map(scale)
scaled_cols = ['y', 'lag_1', 'lag_7', 'lag_14', 'roll_mean_7', 'roll_std_7']
scaled = data.copy()
scaled[scaled_cols] = data[scaled_cols].div(s, axis=0)
scaled['series_id'] = pd.Categorical(scaled['series_id'])
feature_cols = ['series_id', 'lag_1', 'lag_7', 'lag_14',
'roll_mean_7', 'roll_std_7', 'dayofweek']
# categorical_features='from_dtype' needs scikit-learn 1.4 or newer
model = HistGradientBoostingRegressor(
categorical_features='from_dtype',
max_iter=300, learning_rate=0.05, random_state=0,
)
model.fit(scaled.loc[is_train, feature_cols], scaled.loc[is_train, 'y'])
test = data.loc[~is_train].copy()
test['pred'] = model.predict(scaled.loc[~is_train, feature_cols]) * s[~is_train].to_numpy()
test['err_model'] = (test['y'] - test['pred']).abs()
test['err_snaive'] = (test['y'] - test['lag_7']).abs()
print(test.groupby('series_id')[['err_model', 'err_snaive']].mean())The model works on scaled values, but the error is measured in the original units. The seasonal-naive baseline, lag_7, is evaluated per series on the same rows. A global model that cannot beat that baseline on most series has not earned its complexity.
Validating across many series
Validation follows the same rule as before: the future must not influence the past. With many series, apply that rule to a shared calendar.
- Use one cutoff date for all series, as the code above does. A split that holds out the last 20% of rows per series is acceptable, but a shared date is easier to reason about.
- Do not hold out whole series and call it a time split. That tests transfer to new series, which is a different question. It is useful if you expect a cold-start situation, but it does not measure forecast accuracy.
- Keep the
gapbetween train and validation blocks when walk-forward splitting. Because the table is sorted by series and then by date,TimeSeriesSpliton row positions will cut the wrong places. Split on dates instead, and select rows with a date mask.
Report accuracy per series, not only as one pooled number. A pooled MAE is dominated by large series. Scaled metrics such as MASE let you average across series fairly.
Deciding between local and global
| Situation | Better choice | Reason |
|---|---|---|
| Hundreds of short series with shared patterns | Global | Each series alone is too short to learn from |
| A few long series with distinct behaviour | Local | A single model must compromise between them |
| New series appear often | Global with attributes | It forecasts a new series from its attributes and recent lags |
| Series differ by orders of magnitude | Global with scaling | Without scaling, large series dominate the loss |
| You need full per-series control | Local | You can tune and retire models independently |
A middle path is to cluster series by behaviour, or by an attribute such as product category, and fit one global model per cluster.
Common failure modes
- Cross-series leakage from a missing
groupby, as covered above. - Scales computed on the full history, which leak the test period.
- Series with irregular or gappy dates. Reindex each series to a regular frequency before building lags, or the lag of seven rows will not mean seven days.
- Series that stop or start midway. Decide whether a missing period is a zero or an unknown, and be consistent.
- Averaging pooled error and concluding the model is good while it fails on every small series.
Exercise
You stack 200 daily series into one table and compute panel['lag_1'] = panel['y'].shift(1) without grouping. Which rows are affected, and what is the correct fix?
Show answer
The first row of each series (except the first series in the table) receives the last value of the previous series as its lag1, and the same happens for the first rows of lag7 and lag14. This silently mixes series. The fix is `panel.groupby('seriesid')['y'].shift(1), which leaves NaN at the start of each series so dropna` removes those rows. Rolling features need the same grouping.
Exercise
Your global model's pooled MAE looks excellent, but the business complains that forecasts for low-volume products are poor. Give two causes and two changes.
Show answer
Causes: the pooled MAE is dominated by high-volume series, and the squared or absolute loss on unscaled targets makes the model spend its capacity on large series. Changes: divide each series by a training-period scale before fitting (and multiply predictions back), and report per-series or scaled metrics such as MASE instead of one pooled MAE. Adding series attributes or the identifier as a categorical feature also helps the model specialise.