σμimplied vol · KKmax(S−K,0)udβρᵢⱼfat tailsPnL · drawdownyield · TdSₜ = μSₜ dt + σSₜ dWₜC = S·N(d₁) − K·e⁻ʳᵀ·N(d₂)σₚ² = wᵀΣwd₁ = [ln(S/K) + (r + σ²⁄2)T] ⁄ σ√T∂V/∂t + ½σ²S²·∂²V/∂S² + rS·∂V/∂S − rV = 0Sharpe = (Rₚ − R_f) ⁄ σₚVaR₉₉ = μ − 2.33σρ = Cov(X,Y) ⁄ σₓσᵧE[Rₚ] = Σ wᵢ·E[Rᵢ]φ(x) = e^(−x²/2) ⁄ √2πE[Rᵢ] = R_f + βᵢ(E[Rₘ] − R_f)dXₜ = θ(μ − Xₜ)dt + σ dWₜσ²ₜ = ω + α·ε²ₜ₋₁ + β·σ²ₜ₋₁C − P = S − K·e⁻ʳᵀΔ = ∂V/∂S Γ = ∂²V/∂S²p = (e^(rΔt) − d) ⁄ (u − d)rₜ = ln(Pₜ ⁄ Pₜ₋₁)E[Xₜ₊₁ | ℱₜ] = Xₜf* = (bp − q) ⁄ bz = (x − μ) ⁄ σP(N=k) = λᵏe^(−λ) ⁄ k!Θ = −∂V/∂Tν = S·φ(d₁)·√Tmin wᵀΣw s.t. wᵀμ = μ*∫Σ∂∞λ
uantCraft AcademyRoadmapsSkills
Ctrl K
AO
+1.2k Learners
LoginJoin ↗
RoadmapsSkills
AO
+1.2k Learners
Login
  • English
  • Français
  • Español
  • العربية
  • Português
  • Deutsch
  • 日本語
  • 中文
σμimplied vol · KKmax(S−K,0)udβρᵢⱼfat tailsPnL · drawdownyield · TdSₜ = μSₜ dt + σSₜ dWₜC = S·N(d₁) − K·e⁻ʳᵀ·N(d₂)σₚ² = wᵀΣwd₁ = [ln(S/K) + (r + σ²⁄2)T] ⁄ σ√T∂V/∂t + ½σ²S²·∂²V/∂S² + rS·∂V/∂S − rV = 0Sharpe = (Rₚ − R_f) ⁄ σₚVaR₉₉ = μ − 2.33σρ = Cov(X,Y) ⁄ σₓσᵧE[Rₚ] = Σ wᵢ·E[Rᵢ]φ(x) = e^(−x²/2) ⁄ √2πE[Rᵢ] = R_f + βᵢ(E[Rₘ] − R_f)dXₜ = θ(μ − Xₜ)dt + σ dWₜσ²ₜ = ω + α·ε²ₜ₋₁ + β·σ²ₜ₋₁C − P = S − K·e⁻ʳᵀΔ = ∂V/∂S Γ = ∂²V/∂S²p = (e^(rΔt) − d) ⁄ (u − d)rₜ = ln(Pₜ ⁄ Pₜ₋₁)E[Xₜ₊₁ | ℱₜ] = Xₜf* = (bp − q) ⁄ bz = (x − μ) ⁄ σP(N=k) = λᵏe^(−λ) ⁄ k!Θ = −∂V/∂Tν = S·φ(d₁)·√Tmin wᵀΣw s.t. wᵀμ = μ*∫Σ∂∞λ
uantCraft AcademyRoadmapsSkills
Ctrl K
AO
+1.2k Learners
LoginJoin ↗
RoadmapsSkills
AO
+1.2k Learners
Login
  • English
  • Français
  • Español
  • العربية
  • Português
  • Deutsch
  • 日本語
  • 中文
XGBoost skill›Module 4 · Reading and judging the model›Topic 4.1·~50 minAdvanced

Feature importance: gain versus SHAP

Skill positionModule 4 of 4 · Topic 1 of 4
4.1 Feature importance: gain versus SHAP
—Lab score— / 100Total XP—Streak—
Lecture0% read

7 min readCode examples: 6

  1. 01Two ways to ask what the model used
  2. 02Gain: what the trees recorded
  3. 03SHAP: how much each column moved a prediction
  4. 04Explaining one row
  5. 05Where gain and SHAP part
  6. 06What you will build

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.

01

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.

DefinitionFeature importance

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.

02

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.

main.pyPython
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}
  1. 1Only vol drives the target.
  2. 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.

main.pyPython
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}
  1. 1How many splits ask about each column.
  2. 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.

03

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.

prediction = base + Σ contribution of each column(1)base: the average prediction of the model; the contributions (SHAP values) are one number per column and row, and can be positive or negative

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.

main.pyPython
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
  1. 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.

main.pyPython
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.

04

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.

main.pyPython
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.

05

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.

main.pyPython
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.

Importance is not cause

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.

Compute SHAP where you will use the model

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 the real data says56 US stocks; 150 trees of depth 4, fit before 2011, SHAP on 2011 to 2014
Splits on the noise column22%of the splits of the model
Gain share of noise14.1%vol 48.4%, mom 23.2%, rev 14.3%
SHAP share of noise4.0%vol 60.3%, mom 23.9%, rev 11.9%
Additivity gap1.5e-07base + contributions against the prediction

Key takeaways

  • Gain is a training record. It averages how much each column helped the fit when the trees were grown, and credits chance patterns too.
  • SHAP adds up. The contributions of the columns plus the base equal the prediction for every row; XGBoost computes them exactly for trees.
  • Use the absolute value. Average |SHAP| over the rows you care about to get an importance; signs cancel otherwise.
  • Test with noise. Add a random column: a good importance gives it little, and what it does get tells you how much of the model is fitting chance.
Quick check
Your turn. The base of a model is 0.060. For one row the SHAP values of its three columns are +0.012, −0.004 and +0.001. What does the model predict for this row?
Pick an answer.
06

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
Explorer · lab-xg-08
▾ lab-xg-08
▾ data
…
bash · in-browser
learner@quantcraft:~/lab-xg-08$
Python not loaded yetPythonLn 1, Col 1Spaces: 4UTF-8

Reset this topic?

Everything in lab-xg-08 goes back to the starter files and the terminal is cleared. Your current solution will be lost — this can't be undone.

Will be reset
  • main.py → starter code
  • Terminal history and test output
  • Unsubmitted changes
Will be kept
  • Best lab score
  • Your XP and streak
  • Lecture progress and notes