Sub topic 6
Fast exact values for trees with TreeExplainer
This chapter assumes you can fit a scikit-learn style model, use pandas and NumPy, and know what gradient boosting is. It also assumes you know that a SHAP value is one feature's share of the gap between a prediction and the baseline. Here you will see why trees get a faster algorithm and how its settings change the numbers.
Why trees are a special case
The brute-force code earlier in this tutorial visits every subset of features. That costs time exponential in the number of features, so it is unusable beyond about 15 features.
shap.TreeExplainer runs Tree SHAP, which uses the structure of a decision tree. It pushes all feature subsets through the tree at once and merges the paths that lead to the same leaf. The cost grows polynomially with the number of trees, leaves and depth. The result is still exact. It is not an approximation, apart from floating-point error.
It supports scikit-learn forests and gradient boosting, XGBoost, LightGBM, CatBoost and similar tree libraries.
Two ways to remove a feature
A tree cannot simply ignore a feature, so TreeExplainer needs a rule for "missing". The feature_perturbation argument selects the rule.
| Setting | Needs background data | How a missing feature is handled | Baseline |
|---|---|---|---|
| `"tree_path_dependent"` (default when no data is given) | No | Follows both branches, weighted by how many training rows went each way (the node cover) | Mean prediction implied by the tree's training covers |
| `"interventional"` (used when you pass `data`) | Yes | Replaces the feature with values from the background rows | Mean model output over the background rows |
The path-dependent rule can give credit to a feature the model never uses directly, because the cover counts encode correlations in the training data. The interventional rule is closer to the definition from earlier chapters. It costs more, because the work grows with the size of the background sample.
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)
path = shap.TreeExplainer(model)
sv_path = path(X)
background = X.iloc[:100]
interv = shap.TreeExplainer(
model, data=background, feature_perturbation="interventional"
)
sv_int = interv(X)
print(sv_path.base_values[0], sv_int.base_values[0])
for name, sv in [("path", sv_path), ("interventional", sv_int)]:
total = sv.base_values + sv.values.sum(axis=1)
print(name, np.allclose(total, model.predict(X), atol=1e-4))Both explainers reproduce the model's predictions, so additivity holds either way. The baselines and the individual values differ, because each rule defines "feature removed" differently.
Choosing between the two settings
Start with the default for speed. Switch to interventional when the baseline must mean something specific, such as "the average customer in last month's data". A 100-row sample is usually enough, and larger samples slow things down.
Units of the output
TreeExplainer explains the model's raw output. For a regressor, that is the target's units, so the SHAP values above are in disease-progression points. For gradient boosting and XGBoost classifiers, it is the log-odds (raw margin), not the probability. The units are covered in a later chapter.
Common errors
- Passing a pipeline or a non-tree model. TreeExplainer needs the fitted tree model itself, so pass the final estimator and the transformed features.
- Expecting
expected_valueto be a plain number. For multi-output or multi-class models it is an array. - Explaining a very large dataset in one call. Cost grows with rows, so explain a sample.
Exercise
You fit a random forest and call shap.TreeExplainer(model) with no data argument. A colleague wants the baseline to be the average prediction over this month's customers only. What change do you make, and what is the trade-off?
Show answer
Pass this month's customers as the data argument, for example shap.TreeExplainer(model, data=month_df), which switches to the interventional setting. The baseline becomes the mean model output over those rows. The trade-off is longer computation, which grows with the background sample size, so use a sample of about 100 rows.