σμ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
  • 日本語
  • 中文
LightGBM skill›Module 4 · Reading and comparing models›Topic 4.1·~45 minAdvanced

Model interpretation

Skill positionModule 4 of 4 · Topic 1 of 2
4.1 Model interpretation
—Lab score— / 100Total XP—Streak—
Lecture0% read

7 min readCode examples: 4

  1. 01Three answers from the model
  2. 02SHAP values add up
  3. 03Shuffle and see
  4. 04The panel
  5. 05What you will build

Fit LightGBM on three real features and two columns of random noise, and count the splits: the noise columns get 32.4% of them. Look at the gain instead and they get 15.1%; at the SHAP values, 6.6%; shuffle them and the error does not move. Four importances, four stories. This topic builds all four.

01

Three answers from the model

Where we are. The last topics built and scored models. Now the question is why a model says what it says. A trained LightGBM model is a list of trees, and model.booster_.trees_to_dataframe() returns it as a table with one row per node: the feature used at a split (NaN at a leaf) and the gain of the split. Two importances come straight from that table.

DefinitionSplit count

How many times a feature is used in a split, over all the trees. It measures how much the model *uses* a feature, not how much it *needs* it.

DefinitionGain importance

The sum, over the splits that use a feature, of the drop in squared error each split brought on the training rows. It measures how much the model gained from a feature while it was being fitted.

Worked example 1. *Problem:* three features, a (a step: the target jumps by 3 when a > 0), b (a smooth line: 0.5 b) and c (pure noise). A model of 20 small trees: which feature has the most splits and which has the most gain? *Plan:* fit the model, read the table of trees, and count and add. *Steps:* below.

main.pyPython
rng = np.random.default_rng(0)n = 300X = pd.DataFrame({"a": rng.normal(size=n), "b": rng.normal(size=n), "c": rng.normal(size=n)})y = 3 * (X["a"] > 0) + 0.5 * X["b"] + rng.normal(0, 0.3, n)model = lgb.LGBMRegressor(n_estimators=20, learning_rate=0.2, num_leaves=4, min_child_samples=10, n_jobs=1, random_state=0, verbose=-1).fit(X, y)names = list(X.columns)1trees = model.booster_.trees_to_dataframe()2print(split_counts(trees, names))print({k: round(v, 1) for k, v in gain_totals(trees, names).items()})print({k: round(v, 3) for k, v in shares(gain_totals(trees, names)).items()})
{'a': 22, 'b': 37, 'c': 1}
{'a': 1796.5, 'b': 214.0, 'c': 0.4}
{'a': 0.893, 'b': 0.106, 'c': 0.0}
  1. 1One row per node; leaves have no split_feature.
  2. 2Counting the rows of each feature, and adding their gains.

*Check:* the noise column c is used 1 time and brings a gain of 0.4, nothing. But b, the smooth line, has the most splits (37) while a, the step, has 22. The gain tells the opposite story: a brings 1,796.5 (89.3 % of the total) and b only 214.0 (10.6 %). *What to notice:* a step is found in one cut; a line needs many small cuts to be approximated, each worth little. So the feature with the most splits is not the one the model needs most. Gain is the better of the two.

Both numbers come from the training rows. A feature that helped fit the training noise earns splits and gain that will not repeat on new rows. The next two importances look at rows the model did not train on.

02

SHAP values add up

A SHAP value answers a different question: *for this one row, how much did each feature push the prediction away from the average prediction?* LightGBM computes it exactly for trees with model.predict(X, pred_contrib=True): a matrix with one column per feature and a last column with the base value (the average prediction). The defining property is that every row adds up to the prediction.

prediction(row) = base + SHAP(row, feature 1) + SHAP(row, feature 2) + …(1)the base value is the same for every row; a positive SHAP value pushed this row's prediction up, a negative one pushed it down; the last column of pred_contrib is the base

A global importance follows from the local ones: the mean absolute SHAP value of a feature over many rows. Worked example 2. *Problem:* the SHAP values of the first three rows of the toy data, their predictions, and the global importances. *Plan:* call predict with pred_contrib=True, check equation 1 with additivity_gap, then average the absolute values. *Steps:* below.

main.pyPython
rng = np.random.default_rng(0)n = 300X = pd.DataFrame({"a": rng.normal(size=n), "b": rng.normal(size=n), "c": rng.normal(size=n)})y = 3 * (X["a"] > 0) + 0.5 * X["b"] + rng.normal(0, 0.3, n)model = lgb.LGBMRegressor(n_estimators=20, learning_rate=0.2, num_leaves=4, min_child_samples=10, n_jobs=1, random_state=0, verbose=-1).fit(X, y)names = list(X.columns)1contribs = model.predict(X.iloc[:3], pred_contrib=True)print(contribs.round(3).tolist())print(model.predict(X.iloc[:3]).round(3).tolist(), additivity_gap(contribs, model.predict(X.iloc[:3])) < 1e-9)2everything = model.predict(X, pred_contrib=True)print({k: round(v, 3) for k, v in mean_abs_contrib(everything, names).items()})
[[1.481, 0.581, 0.001, 1.378], [-1.334, 0.34, 0.001, 1.378], [1.524, 0.344, 0.001, 1.378]]
[3.441, 0.386, 3.247] True
{'a': 1.434, 'b': 0.372, 'c': 0.003}
  1. 1Columns: a, b, c and then the base value 1.378.
  2. 2Mean of the absolute values over all the rows, base column left out.

*Check:* each row's four numbers add up to its prediction: for the first row 1.481 + 0.581 + 0.001 + 1.378 = 3.441. The base value is 1.378 for every row. The importances are 1.434 for a, 0.372 for b and 0.003 for c. *What to notice:* the SHAP importance of b is a quarter of a's, close to its gain share of 10.6 % and far from its share of the splits. The two measures that look at what the model *did* with a feature agree; the one that counted cuts does not.

03

Shuffle and see

The fourth importance asks nothing of the model's insides. Take rows the model did not train on, shuffle the values of one column so that it no longer matches the target, predict again, and see how much worse the error gets. A feature the model relies on makes the error grow; a feature it ignores changes nothing.

importance(column) = rmse after shuffling the column − rmse before(2)averaged over several random shuffles; computed on rows the model was not fitted on; it can be slightly below 0 for a column that does not help

Worked example 3. *Problem:* the permutation importance of the three toy features, with 5 shuffles each. *Plan:* use the model's own predict. *Steps:* below.

main.pyPython
rng = np.random.default_rng(0)n = 300X = pd.DataFrame({"a": rng.normal(size=n), "b": rng.normal(size=n), "c": rng.normal(size=n)})y = 3 * (X["a"] > 0) + 0.5 * X["b"] + rng.normal(0, 0.3, n)model = lgb.LGBMRegressor(n_estimators=20, learning_rate=0.2, num_leaves=4, min_child_samples=10, n_jobs=1, random_state=0, verbose=-1).fit(X, y)names = list(X.columns)importance = permutation_importance(model.predict, X, y, 5, 0)print({k: round(v, 3) for k, v in importance.items()})
{'a': 1.846, 'b': 0.452, 'c': 0.001}

*Check:* shuffling a raises the error by 1.846, shuffling b by 0.452, shuffling c by 0.001. The order is the same as the gain's and the SHAP's, and the noise column is at zero. (In this toy the rows are the training rows; on real data use rows the model did not see.) *What to notice:* the permutation importance is in the unit of the error: shuffling a costs 1.8 of rmse, which is easy to explain to someone who does not know what a split is.

  • FunctionQuestion it answers
  • split_counts(trees, features)How often is a feature used?leaves are not splits
  • gain_totals(trees, features)How much did a feature gain?sum of split_gain
  • mean_abs_contrib(contribs, features)How large are its SHAP values?base column left out
  • additivity_gap(contribs, pred)Do the SHAP values add up?base column included
  • permutation_importance(predict, X, y, n, seed)What breaks if the column is shuffled?one generator, columns in order
  • spearman(a, b)Do two importances rank the features alike?average ranks for ties
04

The panel

Worked example 4. *Problem:* the size of next month's move from mom, rev and vol on 56 stocks, plus two columns of random numbers that cannot help (noise, normal, and noise2, uniform). Fit on the fit rows (before 2011) and compare the four importances, computing SHAP and permutation importance on the valid rows (2011 to 2014). *Plan:* add_noise for both frames with different seeds, fit, and gather the four measures. *Steps:* below.

main.pyPython
panel = build_panel(load_close())fit, valid, _ = split_panel(panel)X_fit, X_valid = add_noise(fit, 1), add_noise(valid, 2)model = lgb.LGBMRegressor(n_estimators=150, learning_rate=0.05, num_leaves=8, min_child_samples=20, n_jobs=1, random_state=0, verbose=-1).fit(X_fit, fit[TARGET])trees = model.booster_.trees_to_dataframe()counts, gains = split_counts(trees, COLUMNS), gain_totals(trees, COLUMNS)shap = shares(mean_abs_contrib(model.predict(X_valid, pred_contrib=True), COLUMNS))perm = permutation_importance(model.predict, X_valid, valid[TARGET], 5, 0)for column in COLUMNS:    print(f"{column:<7}", counts[column], f"{shares(gains)[column]:.1%}", f"{shap[column]:.1%}", round(perm[column], 5))
mom     229 26.6% 24.0% 0.00048
rev     185 8.4% 11.4% 0.00062
vol     296 49.8% 58.0% 0.00255
noise   139 8.1% 2.8% 7e-05
noise2  201 7.0% 3.9% -6e-05

*Check:* vol is first in all four columns (296 splits, 49.8 % of the gain, 58.0 % of the SHAP importance, 0.00255 of rmse when shuffled). The noise columns are the surprise: noise has 139 splits and noise2 201, which together are 32.4 % of all the splits, more than rev (185) has alone. Their gain is 15.1 %, their SHAP importance 6.6 %, and shuffling them changes the error by 0.00007 and -0.00006, nothing. *What to notice:* LightGBM keeps cutting a noise column because every cut on the fit rows brings a small gain by luck, and a continuous column offers hundreds of places to cut. The split count credits that. The permutation importance, computed on rows the model did not train on, gives the noise what it deserves.

Last, the checks that make your code trustworthy. Your split counts are exactly model.booster_.feature_importance("split"), your gain totals are feature_importance("gain") (gap 0), and the SHAP values add up to the predictions (gap 1.8e-16). How alike do the four rank the five columns? The rank correlations are 0.7 between split counts and gain, 0.9 between gain and SHAP, 0.9 between gain and permutation, and only 0.5 between split counts and permutation.

Do not read causes into importances

An importance says what the *model* uses, not what moves the market. Two correlated features share the credit in an arbitrary way; a feature can be important because it proxies for another. Use importances to check a model for nonsense (a noise column near the top, an identifier that should not matter), not to explain the world.

What the real data says56 US stocks; model fitted before 2011; SHAP and permutation on 2011 to 2014
Most importantvolfirst by splits (296), gain (49.8%), SHAP (58.0%) and permutation
Noise columns, splits32.4%of all the splits, for two columns that carry no information
Noise columns, gain15.1%less, but not zero: luck on the fit rows
Noise columns, SHAP6.6%computed on rows the model did not train on
Noise columns, permutationabout 00.00007 and −0.00006 of rmse

Key takeaways

  • Split counts reward cutting, not need. A smooth or noisy continuous column collects many splits; the count says how often a feature was used, not how much the model needs it.
  • Gain is better, SHAP and permutation are better still. Gain comes from the fit rows; SHAP and permutation importance can be computed on rows the model did not train on.
  • SHAP values add up. base + the SHAP values of a row = its prediction; the mean absolute SHAP value is a global importance.
  • Add a noise column as a ruler. A feature with no information should rank last; if a noise column ranks high in an importance, that measure cannot be trusted.
Quick check
Your turn. Feature X has the most splits of all the features, but a gain share of 3% and a permutation importance of 0. What is the best reading?
Pick an answer.
05

What you will build

The lab follows the lecture. Tasks 1 to 3 read the split counts and the gain from the table of trees and turn them into shares. Tasks 4 and 5 work with SHAP values: the additivity check and the global importance. Task 6 is the permutation importance and task 7 the rank correlation. Task 8 puts the four importances side by side for one model with two noise columns.

Next topic: the capstone. XGBoost and LightGBM on one panel, with the same features, the same splits and the same scores: where do they differ, and how do you tell a real difference from noise?

Lab · what's graded

8 tasks · 100 pts
  • Split counts10 pts
  • Gain totals10 pts
  • Shares5 pts
  • SHAP values add up10 pts
  • A global SHAP importance15 pts
  • Permutation importance20 pts
  • Rank correlation10 pts
  • Four importances on the panel20 pts
Explorer · lab-lg-07
▾ lab-lg-07
▾ data
…
bash · in-browser
learner@quantcraft:~/lab-lg-07$
Python not loaded yetPythonLn 1, Col 1Spaces: 4UTF-8

Reset this topic?

Everything in lab-lg-07 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