A column of random numbers cannot know anything about next month. The trees asked about it in 22% of their splits and gave it 14% of the gain. On rows the model had not seen, it moves the predictions by 4% of the total.
Two ways to ask what the model used
Where we are. The model of the last topics is tuned, regularised and constrained, and it predicts the size of next month's move well enough to beat the average. The next question is what it learned: which columns did the work? Asking is easy; answering honestly takes care, because there are several answers and they disagree.
A number for each column that says how much the model relied on it. There is no single definition. Gain measures the improvement of the fit on the training rows each time a column was used. SHAP measures how far a column moved the predictions you actually look at.
To see how they differ, this topic adds a column of pure noise to the three price features: random numbers, the same sequence every time, with no relation to the target. A good importance should give it almost nothing.
Gain: what the trees recorded
Every split in every tree has a gain: how much the squared error on the training rows fell when the split was made (the number computed in the regularisation topic). The gain importance of a column is the average gain of the splits that use it, written as a share of the total over the columns.
Worked example 1. *Problem:* a tiny model on made-up rows in which only vol drives the target. What does the gain importance say? *Plan:* fit 10 trees of depth 2 on four columns, three of which are noise, and call gain_importance. *Steps:* below.
rng = np.random.default_rng(1)toy = pd.DataFrame({"mom": rng.normal(size=300), "rev": rng.normal(size=300), "vol": rng.uniform(size=300), "noise": rng.normal(size=300)})toy[TARGET] = 2 * toy["vol"] + rng.normal(0, 0.1, 300)1small = fit_model(toy, COLUMNS, 10, 2, 0.3)print({name: round(share, 3) for name, share in gain_importance(small).items()})2
{'mom': 0.0, 'rev': 0.0, 'vol': 1.0, 'noise': 0.0}- 1Only vol drives the target.
- 2Average gain per column, as a share.
*Check:* vol gets all of the credit, 1.0, and the other columns 0.0: with depth 2 and this much signal the trees never needed anything else. *What to notice:* when the signal is strong, gain finds it. The trouble starts when the signal is weak, as with stock returns.
Worked example 2. *Problem:* the real model, with mom, rev, vol and the noise column, trained on the years before 2011 (150 trees of depth 4). What do the trees record? *Plan:* count the splits by column and compute the gain shares. *Steps:* below.
panel = build_panel(load_close())fit = with_noise(split_by_date(panel, "1900-01-01", "2011-01-01"))valid = with_noise(split_by_date(panel, "2011-01-01", "2015-01-01"))model = fit_model(fit)nodes = model.get_booster().trees_to_dataframe()splits = nodes[nodes["Feature"] != "Leaf"]1print(splits["Feature"].value_counts().to_dict(), len(splits))print({name: round(share, 3) for name, share in gain_importance(model).items()})2
{'mom': 591, 'rev': 552, 'vol': 536, 'noise': 466} 2145
{'mom': 0.232, 'rev': 0.143, 'vol': 0.484, 'noise': 0.141}- 1How many splits ask about each column.
- 2The average gain per column, as a share.
*Check:* the noise column is used in 22 % of the 2,000-odd splits, about as often as the real columns (the trees found little to split on, so they split on anything), and its average gain is 0.141 of the total: vol has 0.484, mom 0.232 and rev 0.143. *What to notice:* noise scored the same as rev on gain. Gain is measured on the training rows, where any column can be used to fit chance patterns, and it says nothing about new rows.
SHAP: how much each column moved a prediction
SHAP values answer a different question, for a particular row: of the difference between this row's prediction and the model's average prediction, how much is due to each column? The answer has a property that no other importance has: the pieces add up exactly.
XGBoost computes them for trees quickly and exactly, with pred_contribs=True. Worked example 3. *Problem:* do the contributions add up to the prediction for the real model on the validation years? *Plan:* compute shap_values for the validation rows, add the row sums to the base and compare with model.predict. *Steps:* additivity_gap does it.
values, base = shap_values(model, valid)print(values.shape, round(base, 4))print(f"{additivity_gap(model, valid):.1e}")1print(np.round(values[0], 4).tolist(), round(base + float(values[0].sum()), 4), round(float(model.predict(valid[COLUMNS].iloc[[0]])[0]), 4))
(2688, 4) 0.0619 1.5e-07 [0.0109, -0.0006, -0.0068, 0.0014] 0.0668 0.0668
- 1The largest difference over all the rows.
*Check:* there are 2,688 validation rows and 4 columns, the base is 0.0619, and the largest gap between base + contributions and the prediction is about 1e-7, the rounding of 32-bit numbers. For the first row the contributions are 0.0109, -0.0006, -0.0068, 0.0014 for mom, rev, vol, noise and 0.0619 + 0.0049 = 0.0668, which is the prediction. *What to notice:* the explanation is complete, and the noise column has a small non-zero part in a row, since its random value did fall on some split. Over many rows these parts average out.
To make an importance of this, average the absolute value of each column's contribution over the rows, and write it as a share of the total. The absolute value matters: positive and negative pushes would cancel otherwise.
print({name: round(share, 3) for name, share in shap_importance(model, valid).items()}){'mom': 0.239, 'rev': 0.119, 'vol': 0.603, 'noise': 0.04}*Check:* vol 0.603, mom 0.239, rev 0.119 and noise 0.040. *What to notice:* on rows the model has not seen, the noise column moves the predictions by 4 % of the total, against 14 % of the gain. The SHAP importance is computed where you will use the model; the gain was computed where it was trained.
Explaining one row
The most useful property of SHAP values is that they explain a single prediction. Worked example 4. *Problem:* the first validation row: why did the model predict what it did? *Plan:* sort the contributions of the row by size and read them from the base. *Steps:* explain_row.
print(round(base, 4), [(name, round(value, 4)) for name, value in explain_row(model, valid, 0)])print(valid[["ticker", "mom", "vol"]].iloc[0].to_dict())
0.0619 [('mom', 0.0109), ('vol', -0.0068), ('noise', 0.0014), ('rev', -0.0006)]
{'ticker': 'AAPL', 'mom': 0.6795935638927362, 'vol': 0.06682187884612734}*Check:* starting from 0.0619, the largest push is momentum +0.0109, then volatility -0.0068, noise +0.0014 and reversal -0.0006; the row is AAPL, with a high momentum (0.68) and a low volatility (0.067). *What to notice:* a risk committee can read this: the model expects a bigger move than average because of the stock's momentum, partly offset by its low volatility. The simple method, a table of gains, could not say this for one stock.
Where gain and SHAP part
Worked example 5. *Problem:* put the two importances and the noise side by side. *Plan:* study fits the model on the years before 2011 with the noise column and compares the gain with the SHAP importance on the validation years. *Steps:* below.
result = study(panel)for name in COLUMNS: print(name.ljust(6), round(result["gain"][name], 3), round(result["shap"][name], 3))print(round(result["noise_splits"], 3), f"{result['gap']:.1e}")
mom 0.232 0.239 rev 0.143 0.119 vol 0.484 0.603 noise 0.141 0.04 0.217 1.5e-07
*Check:* the noise column gets 0.141 of the gain and 0.040 of the SHAP importance; vol is first in both (0.484 and 0.603). *What to notice:* both rank vol first and mom second, yet only SHAP gives the noise column something close to the little credit it deserves. Part of it comes from where each is measured: gain on the rows the model fitted, SHAP on rows it has not seen.
A high importance means the model relied on a column, not that changing the column would change the world. Two columns that carry the same information share the credit in an arbitrary way (swap their order and the shares may change). Use importance to find out what to check, not to prove a mechanism.
SHAP on the training rows describes how the model fits the past; SHAP on later rows describes how it behaves in use. Look at both: a column whose SHAP importance is high on the training rows and low on later ones was fitted, not learned.
What you will build
The lab follows the lecture. Task 1 computes the gain importance. Task 2 gets the SHAP values and the base, task 3 checks that they add up to the prediction and task 4 turns them into an importance. Task 5 explains one row. Task 6 puts gain and SHAP side by side on the real panel, with a noise column.
Next topic: you can now say what the model used. The next topic, Time-aware validation, asks whether it learned anything real: how to split the data in time without leaking the future, and why a random split flatters a model.
Lab · what's graded
6 tasks · 100 pts- Gain importance15 pts
- SHAP values25 pts
- Do they add up10 pts
- SHAP importance15 pts
- Explain one row10 pts
- Gain against SHAP25 pts