Sub topic 2
Fast Exact Values for Trees with TreeExplainer
Assume you can train a scikit-learn model and understand NumPy arrays and pandas tables. SHAP explains a prediction by assigning each feature a contribution. For tree ensembles, TreeExplainer computes these contributions efficiently, often exactly for the selected SHAP definition.
TreeExplainer for tree models
Use TreeExplainer with models such as gradient boosting, random forests, and supported XGBoost or LightGBM models.
import numpy as np
import shap
from sklearn.datasets import load_diabetes
from sklearn.ensemble import GradientBoostingRegressor
X, y = load_diabetes(return_X_y=True, as_frame=True)
model = GradientBoostingRegressor(random_state=0).fit(X, y)
explainer = shap.TreeExplainer(model)
sv = explainer(X)
prediction = model.predict(X.iloc[[0]])[0]
reconstructed = sv.base_values[0] + sv.values[0].sum()
print(sv.values.shape)
print(np.isclose(reconstructed, prediction, atol=1e-4))A tree explainer follows the model's tree paths instead of repeatedly calling the model on many masked inputs. This makes it much faster than general-purpose explainers for tree ensembles.
Model-agnostic explainers
For a model without a dedicated explainer, pass a prediction function and background data to shap.Explainer. SHAP can select a model-agnostic method such as permutation or, in some settings, Kernel SHAP.
background = X.iloc[:100]
generic = shap.Explainer(model.predict, background)
generic_values = generic(X.iloc[:20])
print(generic_values.values.shape)These methods estimate contributions by masking features and measuring prediction changes. They work broadly but can require many model evaluations.
The Explanation object
The result is an Explanation object. Its main fields include:
values: SHAP values, usually shaped(rows, features).base_values: the baseline for each row.data: the feature values being explained.feature_names: names used by plots and reports.
For regression, the additivity check is:
base_value + sum(SHAP values) = model prediction
Explain one prediction
A waterfall plot shows how features move one row from the baseline to its prediction.
shap.plots.waterfall(sv[0])Positive values push the prediction higher, while negative values push it lower. The values use the model's output units. For a regression model trained on diabetes measurements, they use the target's units.
Exercise
If the baseline is 150, the SHAP values for one row are 20, -8, and 3, what prediction should the additive explanation produce?
Show answer
165, because 150 + 20 - 8 + 3 = 165.