Sub topic 14
Inspecting Which Features the Model Uses
This chapter assumes you can build lag, rolling and calendar features without leakage, fit a HistGradientBoostingRegressor, and score it on a chronological split. You will learn to ask the fitted model which features it relies on, and to judge how far to trust the answer.
Why inspect a forecasting model
A gradient boosting model with a dozen lag and window features is hard to read directly. Inspection helps in four ways:
- Sanity check. If
lag_7dominates a daily series with weekly seasonality, the model is behaving sensibly. If a feature that should be irrelevant ranks first, suspect leakage. - Feature pruning. Features that add nothing cost compute and add noise.
- Debugging. A model that barely beats the seasonal-naive baseline often turns out to depend almost entirely on the seasonal lag.
- Communication. Stakeholders ask why the forecast moved. A ranked list of drivers is a starting point for that conversation.
Inspection describes what the model does. It does not show what causes the target. Treat every result as a diagnosis of the model, not of the world.
Setup: a model to inspect
The examples below use a synthetic daily series with weekly and yearly seasonality, so they run as shown. They need scikit-learn 1.3 or later.
import numpy as np
import pandas as pd
from sklearn.ensemble import HistGradientBoostingRegressor
from sklearn.metrics import mean_absolute_error
rng = np.random.default_rng(0)
idx = pd.date_range('2023-01-01', periods=730, freq='D')
weekly = np.array([10, 12, 13, 14, 18, 25, 22])[idx.dayofweek]
yearly = 5 * np.sin(2 * np.pi * idx.dayofyear / 365)
series = pd.Series(100 + weekly + yearly + rng.normal(0, 3, len(idx)),
index=idx, name='y')
def make_features(s: pd.Series) -> pd.DataFrame:
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['roll_std_7'] = past.rolling(7).std()
df['dayofweek'] = s.index.dayofweek
return df.dropna()
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'])
print('test MAE', mean_absolute_error(test['y'], model.predict(test[feature_cols])))Permutation importance
Permutation importance answers one question: how much worse does the model get if a feature's values are scrambled? You shuffle one column of a scoring set, predict again, and record the rise in error. A large rise means the model needed that column.
from sklearn.inspection import permutation_importance
result = permutation_importance(
model, test[feature_cols], test['y'],
scoring='neg_mean_absolute_error',
n_repeats=20, random_state=0,
)
imp = pd.DataFrame(
{'mean': result.importances_mean, 'std': result.importances_std},
index=feature_cols,
).sort_values('mean', ascending=False)
print(imp)Because the scorer is negative MAE, each mean is the increase in MAE caused by shuffling that feature. Units are the units of your target, which makes the numbers easy to explain. The std column shows the spread over 20 shuffles. If a feature's mean is smaller than its std, you cannot tell it apart from zero.
Three choices matter for time series:
- Score on a chronological hold-out, not on the training rows. On training data the model has memorized noise, so importance rewards features that help it overfit. Use the test block or a validation fold.
- Shuffling rows is acceptable here. The lags are already materialized as columns, so each row is a self-contained example. Shuffling breaks the link between a feature and its target but does not leak anything.
- Check stability across folds. Repeat the computation on each walk-forward validation block. A feature that is important in one fold and useless in the next suggests the importance reflects a regime, not a stable pattern.
Correlated features split or hide importance
Lag and window features are highly correlated. roll_mean_7 is an average of values near lag_1 through lag_7. When two features carry similar information, shuffling one barely hurts, because the model still reads the other. Both can look unimportant even though the pair is essential.
The remedy is to shuffle related features together, with the same row permutation, and measure the joint effect. Scikit-learn does not provide this, but it takes a few lines.
def grouped_permutation(model, X, y, groups, n_repeats=20, seed=0):
rng = np.random.default_rng(seed)
base = mean_absolute_error(y, model.predict(X))
rows = {}
for name, cols in groups.items():
deltas = []
for _ in range(n_repeats):
Xp = X.copy()
perm = rng.permutation(len(X))
Xp[cols] = X[cols].to_numpy()[perm]
deltas.append(mean_absolute_error(y, model.predict(Xp)) - base)
rows[name] = {'mean': np.mean(deltas), 'std': np.std(deltas)}
return pd.DataFrame(rows).T.sort_values('mean', ascending=False)
groups = {
'lags': ['lag_1', 'lag_7', 'lag_14'],
'window': ['roll_mean_7', 'roll_std_7'],
'calendar': ['dayofweek'],
}
print(grouped_permutation(model, test[feature_cols], test['y'], groups))Compare the grouped result with the single-feature result. If the "lags" group has a large effect while each single lag has a small one, the model uses the lags redundantly. That is a reason to keep the group, not to prune each member.
Partial dependence
Importance says a feature matters. Partial dependence shows how the average prediction changes as that feature moves across its range while the others stay at their observed values.
from sklearn.inspection import partial_dependence
pdp = partial_dependence(model, test[feature_cols], features=['lag_7'],
grid_resolution=20)
for x, y in zip(pdp['grid_values'][0], pdp['average'][0]):
print(f'lag_7={x:7.1f} mean prediction={y:7.1f}')Two things to look for:
- Step shapes. A tree model predicts in steps, so the curve is piecewise constant. That is normal.
- Flat tails. Outside the training range the curve goes flat, because trees cannot extrapolate. If your series trends upward and the top grid values show a flat line, you are seeing the trend limit from the earlier chapter in the model's own behavior.
Partial dependence assumes the feature can vary independently of the others. For lag_1 and roll_mean_7 that is false, so the curve may be averaged over combinations that never occur. Use it for shape, not for exact values.
Impurity-based importance and its problems
The classic GradientBoostingRegressor exposes feature_importances_, computed from how much each feature reduces training loss across splits. HistGradientBoostingRegressor does not provide it. Impurity-based scores have known problems:
- They are computed on training data, so they reward overfitting.
- They favor continuous features with many distinct values over low-cardinality ones such as
dayofweek. - They split credit arbitrarily among correlated features.
Prefer permutation importance on held-out data. Use impurity importance only for a quick look.
Reading the results in a forecasting context
| Observation | Likely meaning | What to do |
|---|---|---|
| `lag_7` dominates, everything else is near zero | Model is close to seasonal naive | Compare MAE with the seasonal-naive baseline. A small gain may not justify the model. |
| `lag_1` dominates on a smooth series | Model leans on persistence | Expect error to compound in recursive multi-step forecasts. |
| A feature that should be irrelevant ranks high | Possible leakage | Re-check shifts and window alignment. |
| Importance changes sharply between folds | Unstable relationship or regime change | Inspect the folds, and consider a shorter training window. |
| A feature has near-zero importance with a large `std` | Noise | Drop it and compare validation error. |
Common errors
- Computing permutation importance on the training set and concluding that a noisy feature matters.
- Reading single-feature scores for correlated lags as if they were independent.
- Treating importance as causal. A high-ranking
lag_1does not mean yesterday causes today. - Ignoring
std. A ranking with overlapping spreads is not a ranking. - Running inspection once on one split and stopping there.
Exercise
After fitting the model, permutation_importance on the test block gives lag_1 a mean increase in MAE of 0.1 with std 0.2, and roll_mean_7 a mean of 0.2 with std 0.3. Grouped permutation of both together raises MAE by 2.5. What should you conclude, and what should you do next?
Show answer
Neither feature can be distinguished from zero alone, but together they matter a lot. They carry overlapping information about recent level, so shuffling one leaves the other available. Keep both, or keep one and check by refitting without the other and comparing walk-forward MAE. Do not drop both because their single-feature scores looked small.