Sub topic 14
Limitations: correlation, causality and cost
This chapter assumes you can fit a scikit-learn style model, compute SHAP values with TreeExplainer or shap.Explainer, and read waterfall, beeswarm and scatter plots. It also assumes you know that a prediction equals the baseline plus the sum of its SHAP values. SHAP is a precise tool, but the numbers it produces are easy to over-read. The main limits are correlated features, causal interpretation and computational cost.
What SHAP does and does not promise
SHAP gives you an exact additive split of one model's prediction, relative to a baseline defined by background data. It promises three things:
- The contributions add up to the prediction minus the baseline.
- Each contribution follows the Shapley fairness rules, given the way "removing a feature" is defined.
- The explanation describes the model you trained.
It does not promise four things:
- That the model matches reality.
- That changing a feature will change the outcome by its SHAP value.
- That features are credited the way a human would split them.
- That the computation is cheap.
Correlated features
To evaluate a coalition of features, SHAP must replace the missing features with something. The two common choices behave differently when features are correlated.
| Setting | How missing features are filled | Consequence with correlated features |
|---|---|---|
| Interventional (`feature_perturbation="interventional"`, and the default for Permutation and Kernel) | Values are sampled from the background data, ignoring the features you kept | Can create rows that never occur in real data, such as a 2 m tall person weighing 40 kg. The model is queried where it was never trained. |
| Tree path dependent (`TreeExplainer` without background data) | Uses the training-sample counts stored in each tree node | Stays closer to the data, but a feature the model never uses can still receive credit because it correlates with one the model does use. |
Credit sharing is the more visible effect. If two features carry the same information, the model may use either one, and SHAP divides the credit according to how the model happened to use them. The code below builds x1 as a near-copy of x0, then compares a model that sees both with a model that sees only one.
import numpy as np
import pandas as pd
import shap
from sklearn.ensemble import RandomForestRegressor
rng = np.random.default_rng(0)
n = 2000
x0 = rng.normal(size=n)
X = pd.DataFrame({
"x0": x0,
"x1": x0 + rng.normal(scale=0.05, size=n), # near-copy of x0
"x2": rng.normal(size=n), # unrelated noise
})
y = 3 * x0 + rng.normal(scale=0.1, size=n)
def mean_abs_shap(model, data):
explainer = shap.TreeExplainer(
model, data.iloc[:200], feature_perturbation="interventional"
)
sv = explainer(data.iloc[:500])
return pd.Series(np.abs(sv.values).mean(axis=0), index=data.columns)
both = RandomForestRegressor(n_estimators=100, random_state=0).fit(X, y)
single = RandomForestRegressor(n_estimators=100, random_state=0).fit(X[["x0", "x2"]], y)
print(mean_abs_shap(both, X))
print(mean_abs_shap(single, X[["x0", "x2"]]))In the first model, the importance that belongs to the signal is spread across x0 and x1. In the second, x0 carries nearly all of it. The data-generating process is the same in both cases. Only the model's choice between redundant features changed.
This leads to three practical rules:
- A small SHAP value for a feature does not mean the feature is unrelated to the target. It may mean a correlated sibling took the credit.
- If features form a natural group, such as the pixels of one region or several lags of one signal, sum their SHAP values and report the group. Because values are additive, the sum is valid.
- If you need stable importance, remove redundant features before training. Do not rely on SHAP to disentangle them.
Background data changes the answer
Chapter material on baselines applies here with extra force. The baseline is the average prediction over the background data, and every SHAP value is measured against it. Two consequences matter in practice:
- A different background gives a different explanation. Explaining a loan applicant against all applicants answers a different question than explaining against approved applicants only.
- A background that is too small gives noisy values for interventional methods. A few hundred rows is a common minimum, and more is better when the model has strong interactions.
Whenever you publish a SHAP result, state which background was used. Treat "the baseline" as a modeling choice and not as a fact about the model.
Causal misreading
SHAP explains how the model reaches its output. It does not explain how the world produces the outcome. Three misreadings are common:
- Treating a SHAP value as an intervention effect. If
incomehas a SHAP value of +0.4 for one customer, raising their income by a unit will not raise the prediction by 0.4. The value is an average over coalitions and background rows, not a slope. It also says nothing about what happens to the other features. - Reading associations as mechanisms. If the model learned that a hospital admission code predicts mortality, SHAP will credit that code. The code may be a marker for a treatment pathway and not a cause.
- Assuming proxies are harmless. Removing a sensitive feature does not stop the model from using correlated proxies. SHAP will show the proxies receiving credit, and that is a useful audit, but it is still not proof of or against causal discrimination.
If your question is "what would happen if we changed X", you need a causal method, experimental data, or at least a causal graph. SHAP can generate hypotheses for those methods but cannot replace them.
Other interpretation limits
- Global importance hides structure. Mean absolute SHAP ranks features by average magnitude. A feature that matters hugely for 2% of rows can rank below one with small effects everywhere. Check the beeswarm plot, not only the bar plot.
- Units are model-specific. For a classifier,
TreeExplaineroften reports log-odds, and probabilities are not additive. A value of +1 in log-odds changes the probability by different amounts depending on where you start. Do not compare SHAP magnitudes across models with different output scales. - Explanations vary across retrains. Two models with equal accuracy can assign very different attributions, especially with correlated features. Check stability by refitting with different seeds or bootstrap samples.
- Additivity can mislead for interactions. Shapley values split an interaction term equally between its features, as in the brute-force example earlier in this tutorial. That is fair by the Shapley axioms, but it can hide that the effect exists only when both features are present. Use interaction values or scatter plots colored by a second feature when that matters.
Computational cost
Exact Shapley values need 2^n coalitions, which is impractical beyond a few dozen features. The cost depends on the explainer.
| Method | Cost behavior | Practical note |
|---|---|---|
| `TreeExplainer`, path dependent | Polynomial in trees, depth and features. Fast. | Usually the cheapest option for tree ensembles. |
| `TreeExplainer`, interventional | Grows with the number of background rows | Keep the background to roughly 100 to 1000 rows. |
| `PermutationExplainer` | Grows with features, background rows and the number of rows explained | Exact for interactions of order two with paired permutations, and a good default. |
| `KernelExplainer` | Model calls grow with `nsamples`, the background size and the rows explained | Slowest. Summarize the background and sample rows. |
The model-agnostic methods call your model many times. The calls are batched, but a slow model such as a large neural network or a remote service will dominate the runtime. The main levers are a smaller background, fewer explained rows, and a lower nsamples or max_evals setting. Lowering those increases variance in the estimates.
import time
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 = shap.kmeans(X, 10) # 10 weighted cluster centers instead of 442 rows
explainer = shap.KernelExplainer(model.predict, background)
start = time.perf_counter()
values = explainer.shap_values(X.iloc[:5], nsamples=200)
print(values.shape, f"{time.perf_counter() - start:.1f}s")shap.kmeans replaces the background with weighted cluster centers, and shap.sample(X, 100) takes a random subset. Both reduce cost, and both change the baseline slightly. Compare the resulting baseline with the full-data mean prediction to see how much.
Deciding how much to trust an explanation
A short routine covers most cases:
- Check the correlation matrix of your features before reading importances.
- Verify additivity: baseline plus the sum of values equals the model output, in the model's own units.
- Refit with another seed and compare the top features.
- Write down the background and the output scale next to every figure.
Exercise
A gradient boosting model for churn gives monthly_spend a mean absolute SHAP value near zero, but total_spend ranks first. In the data, total_spend is almost monthly_spend times tenure. A colleague concludes that monthly spend does not affect churn. What is wrong with that conclusion, and what would you do to test it?
Show answer
The two features are strongly correlated, so the model may rely on total_spend and give monthly_spend little credit even if monthly spend matters. A low SHAP value shows the model did not use the feature, not that the feature is unrelated to churn. To test it, refit the model without total_spend and see whether monthly_spend gains importance, or group the two features and compare the summed SHAP values. Also check stability across random seeds. Any claim about the effect of changing monthly spend needs a causal method or an experiment.
Exercise
You must explain 10,000 rows from a slow model using KernelExplainer, and the first run would take hours. Name three changes that reduce the cost and one drawback shared by them.
Show answer
Summarize the background with shap.kmeans(X, k) or shap.sample(X, m), explain a random subset of rows instead of all 10,000, and lower nsamples. Each change increases the variance of the estimates or shifts the baseline, so the values become less precise or less representative.