Sub topic 17
Interpreting models with importances and SHAP
This chapter assumes you can train a LightGBM or CatBoost model with a validation set, as in the earlier training chapters. It also assumes you know what a regression target and a prediction are. You will learn what the built-in feature importances measure, where they mislead, and how SHAP values explain individual predictions and the model as a whole.
Why built-in importances are not enough
A boosted model can contain thousands of trees. Reading them is not practical, so you usually ask two questions:
- Which features does the model rely on?
- Why did the model predict this value for this row?
Built-in importances answer the first question in a rough way. SHAP answers both, with a more principled method.
Built-in importances
Each library reports several importance types. They measure different things, and their rankings can disagree.
| Library | Type | What it measures |
|---|---|---|
| LightGBM | `split` | How many times the feature is used in a split |
| LightGBM | `gain` | Total loss reduction from splits on the feature |
| CatBoost | `PredictionValuesChange` (default) | Average change in prediction when the feature value changes |
| CatBoost | `LossFunctionChange` | How much the loss gets worse if the feature is removed from the model |
| Either | Permutation importance | Drop in validation score when the feature's column is shuffled |
Split counts reward features with many distinct values, because a continuous feature offers more places to split than a three-level one. Gain is usually the better choice. The scikit-learn wrapper LGBMRegressor defaults to split for feature_importances_, so check which type you are reading.
import lightgbm as lgb
import pandas as pd
from sklearn.datasets import fetch_california_housing
from sklearn.model_selection import train_test_split
X, y = fetch_california_housing(return_X_y=True, as_frame=True)
X_train, X_valid, y_train, y_valid = train_test_split(
X, y, test_size=0.2, random_state=0
)
model = lgb.LGBMRegressor(
n_estimators=2000, learning_rate=0.05, num_leaves=31, verbose=-1
)
model.fit(
X_train,
y_train,
eval_set=[(X_valid, y_valid)],
eval_metric="rmse",
callbacks=[lgb.early_stopping(stopping_rounds=50, verbose=False)],
)
booster = model.booster_
imp = pd.DataFrame(
{
"split": booster.feature_importance(importance_type="split"),
"gain": booster.feature_importance(importance_type="gain"),
},
index=booster.feature_name(),
)
imp["gain"] = imp["gain"] / imp["gain"].sum()
print(imp.sort_values("gain", ascending=False))Compare the two columns. Features that rank high on split but low on gain are used often for small refinements. Features with high gain and few splits make a few large, important cuts.
Limits of built-in importances
- They are computed from the training data, so a feature the model memorized can look important even if it does not generalize.
- They give one global number per feature. They say nothing about direction (does a higher value raise or lower the prediction?) or about a single row.
- When two features are correlated, the model may split on either. The importance gets divided between them or assigned to one almost arbitrarily.
Permutation importance on a validation set fixes the first problem. Use sklearn.inspection.permutation_importance with your fitted model. It costs one extra prediction pass per feature and repeat. It still shares the correlated-feature weakness: shuffling one of two correlated columns creates unrealistic rows.
SHAP values
SHAP (SHapley Additive exPlanations) assigns each feature a contribution to each individual prediction. The contributions come from Shapley values in game theory. Each feature is a player, and the prediction is the payout. A feature's share is its average marginal contribution over all orders in which features could be added.
For a tree model the values satisfy a useful identity:
prediction = base value + sum of the SHAP values for that row
The base value is the average prediction over the background data. For regression the SHAP values are in the units of the target. For a binary classifier they are in log-odds, because that is the space where the trees add up. A SHAP value of +0.8 on a classifier means the feature pushes the log-odds up by 0.8, not the probability.
shap.TreeExplainer computes exact Shapley values for tree ensembles in polynomial time. It does not need to run the model on many perturbed inputs, so it is fast enough for LightGBM and CatBoost models.
import numpy as np
import pandas as pd
import shap
explainer = shap.TreeExplainer(model)
shap_values = explainer.shap_values(X_valid)
# Additivity check: base value + row sum should reproduce the prediction.
base = np.ravel(explainer.expected_value)[0]
reconstructed = base + shap_values.sum(axis=1)
print("max error:", np.abs(model.predict(X_valid) - reconstructed).max())
# Global importance: mean absolute SHAP value per feature.
global_importance = pd.Series(
np.abs(shap_values).mean(axis=0), index=X_valid.columns
).sort_values(ascending=False)
print(global_importance)
shap.summary_plot(shap_values, X_valid)The reconstruction error should be close to zero, with differences only from floating-point rounding. If it is not, you are probably explaining a different model than the one you are predicting with, for example a different number of trees.
The mean absolute SHAP value is the usual global ranking. Unlike split counts, it is in units of the prediction, so the numbers have a direct meaning. The summary plot shows more: each dot is one row, its horizontal position is the feature's SHAP value for that row, and its color is the feature value. A feature whose red dots sit on the right raises the prediction when it is high.
SHAP with CatBoost
CatBoost computes SHAP values natively, and this works with categorical columns without any manual encoding. The returned array has one extra column at the end holding the base value.
from catboost import CatBoostRegressor, Pool
from sklearn.datasets import fetch_california_housing
from sklearn.model_selection import train_test_split
X, y = fetch_california_housing(return_X_y=True, as_frame=True)
X_train, X_valid, y_train, y_valid = train_test_split(
X, y, test_size=0.2, random_state=0
)
cb = CatBoostRegressor(iterations=300, learning_rate=0.1, verbose=0)
cb.fit(X_train, y_train, eval_set=(X_valid, y_valid), early_stopping_rounds=50)
valid_pool = Pool(X_valid, y_valid)
shap_all = cb.get_feature_importance(valid_pool, type="ShapValues")
shap_values = shap_all[:, :-1]
base_value = shap_all[0, -1]
print(shap_values.shape, base_value)
loss_change = cb.get_feature_importance(valid_pool, type="LossFunctionChange")
print(dict(zip(X_valid.columns, loss_change.round(4))))LossFunctionChange needs a dataset that includes labels, which is why the pool is built with y_valid. You can also pass cb to shap.TreeExplainer for the plots shown above.
Pitfalls
- Correlated features. SHAP splits credit between correlated features in a way that depends on the model. Two near-duplicate columns can each show half the importance. Group them or drop one before drawing conclusions.
- Explanation is not causation. SHAP describes how the model uses features. A large value for
incomedoes not mean raising someone's income would change the outcome. - Explain held-out data. SHAP values on training rows reflect what the model memorized. Use validation or test rows for any claim about what generalizes.
- Classification scale. Plots of a binary classifier are in log-odds. Do not read them as percentage points.
- Cost on large data. Exact tree SHAP is fast, but it is still slower than prediction. Explain a random sample of a few thousand rows for global plots.
- Library versions. Older
shapreleases return a list of two arrays for binary classifiers, one per class. Newer releases may return a single array. Printtypeandshapebefore indexing.
Exercise
A LightGBM binary classifier gives a row a SHAP value of +0.5 for the feature plan. A colleague says "being on the pro plan adds 0.5 percentage points to the predicted probability." What is wrong with this statement, and what check would confirm your SHAP values are consistent with the model?
Show answer
SHAP values for a binary LightGBM classifier are in log-odds (the raw score), not probability. +0.5 means plan raises the log-odds by 0.5 for that row, and the change in probability depends on where the row's other contributions put it on the sigmoid curve. To check consistency, compute base value plus the sum of the row's SHAP values and compare it with the model's raw score (predict(..., raw_score=True)). They should match within floating-point error.