Sub topic 5
Choosing the right explainer
This chapter assumes you can train a scikit-learn style model, know what a background sample is, and have seen the rule that a prediction equals the baseline plus the sum of its SHAP values. Here you will learn how the shap library picks an algorithm, and how to override that choice when you need to.
Why there is more than one explainer
The exact Shapley value of a feature averages its marginal contribution over every subset of the other features. With M features that is 2^M subsets, which is impossible to enumerate once M passes about 20. Every SHAP explainer is a different way around that cost. Each one makes a trade-off between three things:
- Exactness: whether the values are exact or estimated.
- Speed: how many model evaluations or how much computation it needs.
- Model access: whether it must call the model as a black box or can read the model's internals.
The explainers fall into two groups:
- Model-specific explainers, such as
TreeExplainer,LinearExplainer,DeepExplainerandGradientExplainer. They use the structure of the model and are usually much faster. - Model-agnostic explainers, such as
ExactExplainer,PermutationExplainerandKernelExplainer. They only need a function that maps inputs to outputs, so they work on anything.
What shap.Explainer does for you
shap.Explainer(model, masker) is a front door. It inspects the arguments and returns an instance of a concrete explainer class. The masker argument is usually your background data, or an object built from it. It defines what "removing a feature" means. The algorithm argument defaults to "auto".
The automatic rules are:
- If the model is a supported tree model, use
TreeExplainer. - If the model is a supported linear model and a masker is given, use
LinearExplainer. - If the model is a plain function and the masker is tabular background data, use
ExactExplainerwhen there are 10 features or fewer, andPermutationExplainerotherwise. - If the masker is a text or image masker, use
PartitionExplainer.
You can check the choice without computing anything:
import shap
from sklearn.datasets import load_diabetes
from sklearn.ensemble import GradientBoostingRegressor
from sklearn.linear_model import LinearRegression
X, y = load_diabetes(return_X_y=True, as_frame=True)
tree_model = GradientBoostingRegressor(random_state=0).fit(X, y)
linear_model = LinearRegression().fit(X, y)
background = X.iloc[:100]
print(type(shap.Explainer(tree_model)).__name__)
print(type(shap.Explainer(linear_model, background)).__name__)
print(type(shap.Explainer(tree_model.predict, background)).__name__)
print(type(shap.Explainer(
tree_model.predict, background, algorithm="permutation"
)).__name__)The four lines print TreeExplainer, LinearExplainer, ExactExplainer and PermutationExplainer. The third call uses ExactExplainer because the diabetes data has exactly 10 features. The fourth call forces a different algorithm on the same function.
The main explainers compared
| Explainer | Works on | Result | Cost |
|---|---|---|---|
| `TreeExplainer` | XGBoost, LightGBM, CatBoost, scikit-learn trees and forests | Exact | Polynomial in tree size, fast |
| `LinearExplainer` | Linear and logistic regression | Exact under its assumptions | Very low |
| `ExactExplainer` | Any function, few features | Exact | 2^M coalitions, only for small M |
| `PermutationExplainer` | Any function | Estimate, exact for interactions up to second order when run with paired permutations | Linear in features per permutation |
| `KernelExplainer` | Any function | Estimate from weighted regression | Slow, grows with samples and background size |
| `DeepExplainer` | TensorFlow and PyTorch networks | Approximation based on DeepLIFT | One backward-style pass per background sample |
| `GradientExplainer` | Differentiable networks | Approximation based on expected gradients | Sampling-based |
| `PartitionExplainer` | Text, images, structured inputs | Estimate using a hierarchy of feature groups | Depends on the masker |
Some details behind the table:
TreeExplaineris the default choice for tabular work. It does not enumerate subsets. It walks the trees and keeps track of how many subsets reach each leaf, which makes exact values cheap. The next chapter covers it in detail.LinearExplainerhas a closed form. For uncorrelated features, the SHAP value is the coefficient times the difference between the feature value and its background mean.PermutationExplainerwalks through random orderings of the features, switching one feature at a time from background to actual value, and records how the output changes. It is the usual fallback for black-box models.KernelExplaineris the original model-agnostic method. It fits a weighted linear regression over sampled coalitions. It still works, butPermutationExplaineris usually faster and gives similar answers.
A decision path
The diagram turns these rules into a sequence of questions.
Using a model-agnostic explainer
For a model with no dedicated explainer, wrap its prediction function and give SHAP a background sample. A background of 50 to 200 rows is usually enough, because the cost of most black-box methods grows with its size.
import shap
from sklearn.datasets import load_diabetes
from sklearn.neighbors import KNeighborsRegressor
X, y = load_diabetes(return_X_y=True, as_frame=True)
knn = KNeighborsRegressor(n_neighbors=10).fit(X, y)
background = shap.sample(X, 100, random_state=0)
explainer = shap.Explainer(knn.predict, background)
sv = explainer(X.iloc[:10])
print(type(explainer).__name__)
print(sv.values.shape)This prints ExactExplainer and (10, 10). A k-nearest-neighbours model has no tree or linear structure, so the call falls through to the black-box branch. Calling explainer(...) returns an Explanation object, which later chapters cover.
To use KernelExplainer instead, use its older interface, which returns a plain array:
kernel = shap.KernelExplainer(knn.predict, background)
values = kernel.shap_values(X.iloc[:5], nsamples=200)
print(values.shape)This prints (5, 10). The nsamples argument sets how many coalitions are evaluated for each row. Larger values reduce estimation noise and increase run time.
Controlling accuracy and cost
For black-box explainers, run time is roughly the number of rows explained, times the number of model evaluations per row, times the background size where it applies. The model's own prediction time often dominates, so a slow model makes everything slow.
Ways to reduce cost:
- Explain a sample of rows rather than the whole dataset when you only need global plots.
- Shrink the background with
shap.sampleorshap.kmeans. The second one summarises the data with weighted cluster centres. - Lower
max_evalsonPermutationExplainer, ornsamplesonKernelExplainer. Lower values give noisier attributions. - Batch the prediction function so it handles many rows in one call. Most of the time spent by black-box explainers goes into repeated model calls.
PermutationExplainer requires max_evals to be at least 2 × the number of features + 1. If you set it lower, shap raises an error that states the minimum.
Common errors
- Passing
model.predictwhen a specialised explainer exists. The result is correct but slower, and it ignores tree structure. Pass the model object. - Omitting the background for a black-box function.
shap.Explainer(f)has nothing to mask with, so it fails. A function needs a masker or background data. - Using
predictwhen you want probabilities. For a classifier,predictreturns class labels. Passing it as the function gives attributions for a step function that jumps between classes. Usepredict_proba, or a wrapper that returns one column. Output units are covered in a later chapter. - Treating estimated values as exact. The additivity check holds for
PermutationExplainerandKernelExplainer, but individual values can shift between runs. Fix the random seed or increase the evaluation budget when you compare results. - Running
KernelExplaineron a large background and a big dataset. Time grows quickly. Switch toPermutationExplainerfirst. - Passing a pipeline that includes preprocessing. Explain either the final model on the transformed features, or the whole pipeline's prediction function on the raw features. The attributions describe whichever columns you pass in. Mixing the two gives values that are hard to map back to your inputs.
Practical rules of thumb
- Start with
shap.Explainer(model)for tree models andshap.Explainer(model, background)for linear ones. Print the class name to confirm what you got. - For a black box, use
shap.Explainer(predict_fn, background)and let it choose between exact and permutation. - Use
KernelExplaineronly when you have a reason, such as reproducing older results. - For neural networks, try
DeepExplainerorGradientExplainerfirst. Fall back toPermutationExplainerwith an image or text masker when those do not support your layers.
Exercise
You have a scikit-learn Pipeline that ends in a support vector machine, and the input has 40 numeric columns. You want local explanations for 200 rows. Which explainer will shap.Explainer(pipeline.predict, background) select, why can it not select ExactExplainer, and what is one way to cut the run time?
Show answer
It selects PermutationExplainer, because the function is a black box with a tabular background and has more than 10 features. ExactExplainer would need 2^40 coalitions, which is not feasible. To cut run time, shrink the background to around 50 to 100 rows with shap.sample or shap.kmeans, explain only a subset of rows, lower max_evals, or make pipeline.predict handle large batches in one call.