Sub topic 6
Fast exact values for trees with TreeExplainer
This chapter assumes you can train a scikit-learn style tree ensemble and use pandas and NumPy. It also assumes you know the ideas from the earlier chapters: a SHAP value is a Shapley value, the baseline comes from the background data, and a prediction equals the baseline plus the sum of its SHAP values.
The brute-force code in the first chapter evaluates the model on every subset of features. That is 2^n evaluations per feature set, which is impossible for realistic n. shap.TreeExplainer avoids this by using the structure of decision trees. It returns exact Shapley values in polynomial time.
Why trees are special
A decision tree has a small number of leaves. Each leaf is reached by a path of conditions on a few features. Tree SHAP (the algorithm behind TreeExplainer) tracks, for each leaf, which feature subsets would send a row down that path. It does this for all subsets at once, with a dynamic-programming recursion. It does not enumerate subsets.
For an ensemble of T trees with at most L leaves and depth D, the cost per explained row is O(T·L·D²). Because the model output is a sum of tree outputs, and Shapley values are linear, the per-tree values add up to the ensemble's values. The result is exact. It is not a sampling estimate, so it has no sampling noise and repeated runs give the same answer.
The depth term matters. Very deep trees, such as a fully grown random forest, are much slower than shallow boosted trees.
Which models it supports
TreeExplainer reads the internal tree structure of the fitted model. It supports:
- scikit-learn
DecisionTree,RandomForest,ExtraTreesandGradientBoostingmodels - XGBoost
- LightGBM
- CatBoost
It cannot explain a model that only exposes a predict function, and it cannot explain a pipeline object. Pass the final fitted tree model, and pass the features as that model sees them (after any preprocessing).
Two ways to remove a feature
A tree path needs a rule for features that are "absent" from the coalition. TreeExplainer offers two rules through the feature_perturbation argument.
| Setting | Background data | How absent features are handled | Cost |
|---|---|---|---|
| `"tree_path_dependent"` | Not needed | Follows both branches of a split on an absent feature, weighted by how many training rows went each way (the node cover) | Fastest |
| `"interventional"` | Required (`data=`) | Replaces the absent feature with values from background rows | Grows with background size |
If you call shap.TreeExplainer(model) with no data, you get the path-dependent mode. If you pass data=, you get the interventional mode, which matches the "masking with background data" definition from earlier in this tutorial. The baseline differs too. In path-dependent mode it is the cover-weighted average of the model output, which is computed from the trees themselves. In interventional mode it is the average prediction over your background rows.
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)
rows = X.iloc[:200]
background = X.iloc[:100]
path_explainer = shap.TreeExplainer(model)
interv_explainer = shap.TreeExplainer(model, data=background)
for name, explainer in [("path-dependent", path_explainer),
("interventional", interv_explainer)]:
sv = explainer(rows)
reconstructed = sv.base_values + sv.values.sum(axis=1)
ok = np.allclose(reconstructed, model.predict(rows), atol=1e-4)
print(name, "baseline:", round(float(np.ravel(explainer.expected_value)[0]), 3),
"additive:", ok)
print("mean prediction on background:",
round(float(model.predict(background).mean()), 3))Both explainers reproduce the prediction exactly, because local accuracy holds in both modes. The baselines differ slightly. The interventional baseline equals the mean prediction on the background rows. The path-dependent baseline is tied to the training data that built the trees.
Choosing between the modes
Use the interventional mode when you want the explanation to follow the definition from the earlier chapters. Features the model never splits on get a SHAP value of exactly zero. You also control the reference population, which matters when "typical" means something specific, such as only approved loan applicants.
Use the path-dependent mode when you have no background data handy or when speed matters most. Be aware of its known quirk. Because it follows branches by training-data cover, it can give credit to a feature that is correlated with a feature the model really uses, even if the model never splits on it. Read it as "how the model behaves on data like the training set". Do not read it as a strict statement about which inputs the model consumes.
A background of 100 to a few hundred rows is usually enough for stable averages. Cost grows roughly linearly with its size. shap.sample(X, 100) draws a random subset, and shap.kmeans(X, 50) summarizes the data with weighted cluster centers.
The model_output argument
model_output chooses which quantity gets explained.
"raw"(the default) explains the model's native margin. For a boosted classifier, that is log-odds. For a regressor, it is the predicted value."probability"explains the predicted probability. It requires background data (interventional mode)."log_loss"explains the model's loss for each row. It also requires background data, and the explainer must be given the labels when it computes values.
The next chapters cover units in more detail. The point here is that additivity holds in whichever space you choose.
from sklearn.datasets import load_breast_cancer
from sklearn.ensemble import GradientBoostingClassifier
Xc, yc = load_breast_cancer(return_X_y=True, as_frame=True)
clf = GradientBoostingClassifier(random_state=0).fit(Xc, yc)
sample = Xc.iloc[:50]
raw = shap.TreeExplainer(clf)(sample)
margin = raw.base_values + raw.values.sum(axis=1)
print("log-odds additive:", np.allclose(margin, clf.decision_function(sample), atol=1e-4))
prob = shap.TreeExplainer(clf, data=Xc.iloc[:100], model_output="probability")(sample)
proba = prob.base_values + prob.values.sum(axis=1)
print("probability additive:", np.allclose(proba, clf.predict_proba(sample)[:, 1], atol=1e-3))Common errors
- Additivity check failure. By default,
explainer(X)checks that baseline plus SHAP values matches the model's output. It raises an error when they differ by more than a small tolerance. A mismatch usually means the explainer saw different data than the model did, for example a column order change or a missing preprocessing step. XGBoost models with float32 rounding can also trigger it. Fix the cause first.check_additivity=Falsehides the symptom and is a last resort. - Wrong output shape for classifiers. Some models, such as random forest classifiers, return one set of values per class, so the array has an extra class axis. Select the class you care about before plotting.
- Passing a pipeline. Extract the fitted estimator and pass transformed features. Feature names then come from the transformed columns, not the raw ones.
- Treating the baseline as a single number.
base_valuesin the Explanation object has one entry per row. With tree models these entries are identical, but code should not assume they are scalars.
Interaction values
Only TreeExplainer can compute SHAP interaction values exactly and quickly. The call explainer.shap_interaction_values(rows) returns an array of shape (n_rows, n_features, n_features). The diagonal holds each feature's main effect, and the off-diagonal entries split the pairwise interaction effects. A later chapter covers reading them.
Exercise
You call shap.TreeExplainer(model) on a fitted XGBoost classifier, with no data argument. A colleague says the baseline will be the mean prediction over your test set. Is that right, and what would you change to make it true?
Show answer
No. With no data argument, TreeExplainer uses tree-path-dependent mode, so the baseline comes from the trees' node covers, which reflect the training data. To make the baseline the mean prediction over a chosen set of rows, pass those rows as data, as in shap.TreeExplainer(model, data=background), which selects interventional mode. For a classifier whose raw output is log-odds, the baseline is then the mean log-odds over those rows. Add model_output="probability" if you want it in probability units.
Exercise
A model never splits on the feature "zipcode", but it uses "region", which is strongly correlated with it. Which TreeExplainer mode can give "zipcode" a nonzero SHAP value, and which gives it exactly zero?
Show answer
The tree-path-dependent mode can give "zipcode" a nonzero value, because it weights branches by training-data cover and so shares credit with correlated features. The interventional mode gives "zipcode" exactly zero, because the model's output never depends on it when it is replaced by background values.