Sub topic 7
Explaining any model with Permutation and Kernel methods
TreeExplainer is fast because it uses the structure of trees. Many models have no such structure, such as neural networks, support vector machines, stacked pipelines, or a function that calls an external service. SHAP still explains these, because it only needs to call the model. This chapter covers the two main ways it does that, Permutation and Kernel, and the costs and trade-offs of each.
You should already be comfortable with Shapley values, background data, the baseline, and the additivity property (prediction = baseline + sum of SHAP values) from earlier chapters. You should also know how to fit a scikit-learn model and slice a pandas DataFrame.
What "model-agnostic" means
A model-agnostic explainer treats the model as a black box. It only asks one question many times: what does the model output for this input?
To estimate a Shapley value, the explainer needs the model's output when only some features are known. The model cannot accept a missing feature, so the explainer replaces each "removed" feature with a value taken from the background data. This is the masking idea from the background-data chapter. Every method in this chapter is a different way to choose which masked inputs to try, and how to combine the outputs.
The exact definition sums over all 2^n subsets of features. For 10 features that is 1,024 subsets per row, which is fine. For 50 features it is about 10^15, which is impossible. Approximate methods sample instead.
The generic entry point: `shap.Explainer`
The simplest way to explain a black box is to pass a prediction function and a background sample to shap.Explainer. It inspects what you gave it and picks an algorithm.
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)
background = X.iloc[:100]
explainer = shap.Explainer(model.predict, background)
sv_agnostic = explainer(X.iloc[:20])
print(type(explainer).__name__)
print(sv_agnostic.values.shape) # (20, 10)We pass model.predict, a plain function, instead of the model. That hides the tree structure, so SHAP cannot choose TreeExplainer. A DataFrame passed as the second argument is wrapped in an independent masker, which draws replacement values for each feature separately from the background rows. SHAP keeps at most 100 background rows by default.
When the model is a function, the automatic choice depends on feature count. With 10 or fewer features, SHAP uses the Exact algorithm, which enumerates every subset. With more than 10, it uses Permutation. The diabetes data has exactly 10 features, so the code above runs the exact algorithm. To force a specific algorithm, name it.
perm = shap.Explainer(model.predict, background, algorithm="permutation")
sv_perm = perm(X.iloc[:5], max_evals=500)
recon = sv_perm.base_values + sv_perm.values.sum(axis=1)
print(np.allclose(recon, model.predict(X.iloc[:5]), atol=1e-4)) # TrueThe final line checks additivity, the property from the earlier chapter. It holds for Permutation SHAP by construction, as the next section explains.
Permutation SHAP
Permutation SHAP estimates Shapley values from random feature orderings. For one row, it repeats this loop:
- Pick a random order of the features, for example
bmi, age, s5, .... - Start with every feature masked (replaced from the background). Record the model output.
- Switch features to their real values one at a time, in that order. After each switch, call the model again.
- The change in output at each step is the marginal contribution of the feature just switched.
- Repeat with the order reversed, then average across all orderings.
Each ordering costs about 2n model calls for n features, because SHAP runs the forward and reverse pass together. Running both is called antithetic sampling. It cancels much of the sampling noise. It also makes the result exact for models whose interactions involve at most two features.
Every ordering's contributions telescope. The sum of the steps equals the output with all features real minus the output with all features masked. So each ordering gives values that add up to the prediction minus the baseline, and so does their average. This is why additivity holds exactly for Permutation SHAP, even when only a handful of orderings are sampled.
The main control is max_evals, the budget of model calls per row. A larger budget means more orderings and less noise. It must be at least 2n + 1. The default is 500, which is too small for wide data. With 200 features, 500 calls cover only about one ordering, so the explanation is dominated by that one order. Raise max_evals to several thousand and compare two runs. If the results differ visibly, the estimate is still noisy.
Kernel SHAP
Kernel SHAP, from the original SHAP paper, takes a different route. It samples coalitions, which are subsets of features marked as "present". For each coalition, it builds a hybrid input and calls the model. It then fits a weighted linear regression whose coefficients are the SHAP values.
The weights come from the Shapley kernel. Coalitions with very few or very many present features get large weights, because those tell you the most about a single feature. The empty and full coalitions get infinite weight. In practice, they become hard constraints. The fit must reproduce the baseline and the prediction, so additivity also holds exactly here.
summary = shap.kmeans(X, 10) # 10 weighted cluster centres as the background
kernel = shap.KernelExplainer(model.predict, summary)
kv = kernel.shap_values(X.iloc[:5], nsamples=500)
print(kv.shape) # (5, 10)
print(kernel.expected_value) # the baseline
recon = kernel.expected_value + kv.sum(axis=1)
print(np.allclose(recon, model.predict(X.iloc[:5]), atol=1e-4)) # TrueKernelExplainer is an older interface than shap.Explainer. It returns plain NumPy arrays instead of an Explanation object, and the baseline lives in expected_value. If you want the plotting functions from the earlier chapters, wrap the output:
sv_kernel = shap.Explanation(
values=kv,
base_values=np.full(5, kernel.expected_value),
data=X.iloc[:5].values,
feature_names=list(X.columns),
)
shap.plots.waterfall(sv_kernel[0])Controlling Kernel SHAP's cost
Kernel SHAP is the slowest explainer in the library. Its cost is roughly nsamples × (background rows) model calls per explained row, because each hybrid input is evaluated against every background row. This is why we passed shap.kmeans(X, 10) instead of the full dataset. Summarizing 10 weighted centres makes it about 100 times cheaper than using 1,000 raw rows. The alternative is shap.sample(X, 100), which draws a random subset.
Other settings:
nsamples="auto"(the default) uses 2 × features + 2048 coalitions. When there are few enough features to enumerate every coalition, it enumerates them and the result is exact.l1_regcontrols feature selection before the regression. Leave it at its default unless you have hundreds of features.
Choosing between them
| Property | Exact | Permutation | Kernel |
|---|---|---|---|
| Interface | `shap.Explainer` | `shap.Explainer` | `shap.KernelExplainer` |
| Accuracy | Exact | Sampled, exact for pairwise interactions | Sampled, regression noise |
| Additivity | Exact | Exact | Enforced by the constraints |
| Typical use | 10 or fewer features | Default for functions with more features | Legacy code, small problems |
| Background handling | Independent masker | Any masker | `kmeans` or `sample` summary |
| Returns | `Explanation` | `Explanation` | NumPy array |
For a new project, start with shap.Explainer and let it choose. Use Permutation for any model with more than 10 features. Reach for Kernel SHAP mainly when you maintain code that already uses it. If the model is a tree ensemble, a linear model, or a deep network with a dedicated explainer, use that explainer, which is much faster.
Comparing the approximations to a reference
A practical check is to run a fast explainer and a slow one on the same rows and compare them. Differences come from two sources. One is sampling noise, which shrinks as you raise max_evals or nsamples. The other is a different definition of masking. For example, TreeExplainer with its default settings uses tree paths instead of a background sample, so it will not match a model-agnostic result exactly. To compare like with like, give TreeExplainer the same background and feature_perturbation="interventional".
tree = shap.TreeExplainer(
model, data=background, feature_perturbation="interventional"
)
sv_tree = tree(X.iloc[:5])
diff = np.abs(sv_tree.values - sv_perm.values).max()
print(diff) # small, since both use the same backgroundIf this difference is large, suspect either too small a budget or different background samples.
Common mistakes
- Passing the model object when you need a function. For a classifier, pass
model.predict_probaor a wrapper that returns the one output you want. Otherwise the output may be class labels, which are not smooth, so SHAP values for them are not useful. - Using the whole training set as the background. Runtime grows with background size. Use 50 to 200 rows or a k-means summary.
- Setting
max_evalsbelow 2n + 1.Permutationraises an error. Increase the budget instead of reducing the feature count. - Reading small differences as signal. With sampled estimators, values that differ by less than the run-to-run noise are the same. Run twice with different seeds on a few rows and see how much they move.
Exercise
You have a neural network with 40 input features wrapped as a function predict(X). You call shap.Explainer(predict, background)(X_test) with the default settings. Which algorithm does SHAP choose, why might the result be noisy, and what two changes would reduce the noise or cost?
Show answer
With more than 10 features and a function as the model, SHAP chooses the Permutation algorithm. The default max_evals of 500 allows only about six orderings of 40 features (each costs about 2 × 40 calls), so the estimate depends heavily on those few random orders. To reduce the noise, raise max_evals (for example to 5,000) when you call the explainer, and compare two runs to check they agree. To keep the cost under control, use a small background of 50 to 200 rows or a shap.kmeans summary, and explain a sample of test rows instead of all of them. Additivity holds either way, so a check that the baseline plus the sum of SHAP values equals the prediction will pass even when the estimate is noisy. It cannot be used to judge the noise.