SHAP: dividing a prediction fairly
Shapley values share a prediction's gap from a baseline among the features. Build one by hand, read the beeswarm and waterfall, and resist reading it as cause.
What runs in CodeSplash
- XGBoost Verified in Python and R
- LightGBM Verified in Python and R
- Elastic net Verified in Python and R
- Linear / logistic regression Verified in Python and R
You will be able to
- Compute Shapley values by averaging over arrival orders
- Read beeswarm, dependence and waterfall charts
- Say what SHAP does and doesn't tell you
Why average over orders?
PredictPredict first
The model is , and absent features are set to 0. Row: , . If arrives first, what does each feature's arrival add?
Reveal
The second arrival gets everything. alone gives . Then adds all of 2. In the other order, takes it all. Averaging over both orders gives each feature a fair 1. That's why one order is arbitrary, and all orders aren't.
Build one
ExploreChange Order features arrive and watch the credit move. Press credit from one order only to see how arbitrary that is. Then use the check: with the multiplying model, set a row where is far from zero and still gets no credit.
DExplorable · Build a Shapley value
How can a prediction be divided fairly among the features that produced it?
How much of the gap between this prediction and the baseline will go to x1?
Model
Order features arrive
f = 3x₁x₂ + x₃
Bar heights are the size of each average credit; the note under each bar shows its credit in the one order chosen above. Orange adds to the prediction, blue subtracts.
Commit your prediction above to see the result
Make your prediction to see the result.
Change Baseline for absent features. A Shapley value is always relative to a baseline: "compared with what?"
Notebook exercise · ~15 min
Exact Shapley values and the baseline
Compute exact Shapley values for a three-feature model by enumerating coalitions, check that they add up, and see them change with the baseline.
- Shapley values against a zero baseline
Feature j's Shapley value averages its marginal contribution value(S + j) − value(S) over every coalition S of the other features, with weight |S|! (n − |S| − 1)! / n! (n = 3). Store the three Shapley values of
x_staragainstbase_zeroinphi_zero.Show a solution
Pythondef shapley(x, base): phi = np.zeros(3) for j in range(3): others = [k for k in range(3) if k != j] for size in range(3): for S in itertools.combinations(others, size): w = math.factorial(size) * math.factorial(2 - size) / math.factorial(3) phi[j] += w * (value(list(S) + [j], x, base) - value(list(S), x, base)) return phi phi_zero = shapley(x_star, base_zero)Rshapley <- function(x, base) { sapply(0:2, function(j) { others <- setdiff(0:2, j) total <- 0 for (size in 0:2) { sets <- if (size == 0) list(integer(0)) else combn(others, size, simplify = FALSE) for (S in sets) total <- total + factorial(size) * factorial(2 - size) / 6 * (value(c(S, j), x, base) - value(S, x, base)) } total }) } phi_zero <- shapley(x_star, base_zero) - Do they add up?
Shapley values are efficient: they add up to f(x) − f(base). Store
True(R:TRUE) inadds_upif the sum ofphi_zerois within 1e-9 of f(x_star) − f(base_zero), elseFalse.Show a solution
Pythonadds_up = bool(abs(phi_zero.sum() - (f(x_star) - f(base_zero))) < 1e-9)Radds_up <- abs(sum(phi_zero) - (f(x_star) - f(base_zero))) < 1e-9 - Change the baseline
Store the Shapley values of the same prediction against
base_meaninphi_mean. Which feature's attribution changes sign or size the most?Show a solution
Pythonphi_mean = shapley(x_star, base_mean)Rphi_mean <- shapley(x_star, base_mean)
In the app this opens as a Python or R notebook with the sample data, and its checks mark your progress.
Exact, or estimated?
ReadTrying all orders is exponential, so implementations cut corners, some safely.
- TreeSHAP: exact for tree ensembles, using tree structure. On XGBoost and LightGBM.
- SHAP (linear): exact for linear models.
- KernelSHAP: an estimate for any model, and much slower.
The app labels which you get. TreeSHAP values live on the model's raw scale (log-odds for two classes), and KernelSHAP on the probability scale.
Read the charts
ExploreEach row is a feature, and each dot is one prediction. Right pushes the prediction up. Color shows the feature's value. Look for a feature where red dots all lie on one side.
View data
| feature | SHAP value (log-odds) | feature value (rank-scaled) |
|---|---|---|
| glucose | 0.2501 | 0.6740 |
| BMI | 0.1263 | 0.4910 |
| age | 0.0884 | 0.6480 |
| pedigree | −0.3025 | 0.0370 |
| pregnancies | 0.0770 | 0.5690 |
| blood pressure | −0.1049 | 0.1230 |
| glucose | 0.3318 | 0.6080 |
| BMI | −0.7429 | 0.0030 |
| age | 0.2739 | 0.6810 |
| pedigree | 0.2384 | 0.7150 |
| pregnancies | −0.2439 | 0.0260 |
| blood pressure | −0.0316 | 0.3600 |
| glucose | −0.8582 | 0.1400 |
| BMI | −0.3809 | 0.2200 |
| age | −0.2396 | 0.2930 |
| pedigree | 0.0842 | 0.6400 |
| pregnancies | −0.1716 | 0.0910 |
| blood pressure | −0.1011 | 0.0460 |
| glucose | −0.3719 | 0.4570 |
| BMI | 0.0242 | 0.5250 |
| age | 0.1298 | 0.5910 |
| pedigree | −0.2582 | 0.1220 |
| pregnancies | 0.0667 | 0.6390 |
| blood pressure | 0.1171 | 0.9120 |
| glucose | 0.6998 | 0.8470 |
| BMI | 0.7228 | 0.9990 |
| age | −0.5405 | 0.0410 |
| pedigree | 0.2389 | 0.7990 |
| pregnancies | −0.1529 | 0.1120 |
| blood pressure | 0.0083 | 0.6030 |
| glucose | −0.9955 | 0.0140 |
| BMI | 0.5194 | 0.8710 |
| age | 0.2168 | 0.6570 |
| pedigree | −0.2619 | 0.1260 |
| pregnancies | −0.2193 | 0.1420 |
| blood pressure | 0.1341 | 0.9780 |
| glucose | −0.1617 | 0.3690 |
| BMI | −0.0334 | 0.4970 |
| age | 0.3667 | 0.9080 |
| pedigree | 0.3055 | 0.9370 |
| pregnancies | −0.1995 | 0.1390 |
| blood pressure | 0.0439 | 0.6410 |
| glucose | 0.6085 | 0.8140 |
| BMI | 0.5847 | 0.8280 |
| age | 0.4300 | 0.8090 |
| pedigree | −0.2783 | 0.0600 |
| pregnancies | 0.1266 | 0.7150 |
| blood pressure | −0.1054 | 0.1620 |
| glucose | 0.6249 | 0.7950 |
| BMI | −0.3003 | 0.3550 |
| age | −0.5218 | 0.0940 |
| pedigree | −0.2607 | 0.0510 |
| pregnancies | 0.1897 | 0.9090 |
| blood pressure | −0.0793 | 0.0940 |
| glucose | 0.0900 | 0.5890 |
| BMI | 0.6476 | 0.9720 |
| age | −0.0168 | 0.3380 |
| pedigree | 0.3354 | 0.8950 |
| pregnancies | 0.1604 | 0.7980 |
| blood pressure | 0.0353 | 0.5710 |
First 60 of 1560 rows.
Beeswarm: the whole model. Dependence: one feature's value against its SHAP. Waterfall: one row's sum, from the base value to the final prediction.
View data
| feature | SHAP value (log-odds) | value |
|---|---|---|
| glucose | 1.222 | 168 |
| BMI | 0.5650 | 38.2 |
| age | 0.3460 | 51 |
| pedigree | −0.2740 | 0.21 |
| pregnancies | 0.1140 | 3 |
| blood pressure | −0.0630 | 74 |
| 4 other features | 0.0630 | — |
Not a cause
ReadSHAP explains how the model arrived at a number. If previous_claims has a large contribution, the model leans on it. It doesn't mean that changing claims would change risk.
Correlated features split credit in arbitrary-looking ways too, as both can stand in for the same signal. Use SHAP to debug and to explain the model. Use causal methods for causal claims.
Check your understanding
CheckpointCheck yourself
Base value 0.30. Contributions: glucose , BMI , and age is the only other feature. The prediction is 0.55. What is age's contribution?
Show the answer
Answer: 0.15
The contributions add up to the gap: , so age is .
Check yourself
The model never reads . What is 's Shapley value for any row?
Show the answer
Answer: 0
It adds nothing in any order, so the average is zero. This is the "dummy" property.
Check yourself
A SHAP plot shows that a high discount pushes predicted churn up. What can you conclude?
Show the answer
Answer: b
Discounts may be targeted at customers likely to leave. To learn the effect of a discount, you need an experiment or a causal design.
Check yourself
Which learner gives you exact SHAP values at little cost?
Show the answer
Answer: a
Tree structure makes the exact sum tractable. The last two need KernelSHAP's estimate.
Explain a run
In the appIn a run's Explanations tab, the method under One prediction is labeled SHAP (TreeSHAP), SHAP (linear) or SHAP (KernelSHAP), depending on the learner. It's ticked by default, so press Explain. Set On to the rows you care about.
import pandas as pd
import shap
from xgboost import XGBClassifier
df = pd.read_csv("pima.csv")
X, y = df.drop(columns="diabetic"), df["diabetic"]
model = XGBClassifier(n_estimators=40, max_depth=3).fit(X, y)
values = shap.TreeExplainer(model).shap_values(X)
print(pd.Series(abs(values).mean(axis=0), X.columns).sort_values(ascending=False).round(3))library(xgboost)
df <- rbind(MASS::Pima.tr, MASS::Pima.te)
X <- as.matrix(df[, setdiff(names(df), "type")])
y <- as.numeric(df$type == "Yes")
fit <- xgb.train(list(max_depth = 3, objective = "binary:logistic"), xgb.DMatrix(X, label = y), nrounds = 40, verbose = 0)
contrib <- predict(fit, X, predcontrib = TRUE)
round(sort(colMeans(abs(contrib[, colnames(X)])), decreasing = TRUE), 3)Recap
Recap- A Shapley value is a feature's average contribution over all arrival orders, and contributions add up to the gap from the base value.
- TreeSHAP and linear SHAP are exact. KernelSHAP estimates.
- SHAP explains the model, not the world.
Concepts in this lesson