Skip to content

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.

Applied ~13 min9 steps

What runs in CodeSplash

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

Read first

01

Fair shares

Read

A prediction is 0.720.72, and the average prediction is 0.330.33. So 0.390.39 has to be shared out among the features. How?

A Shapley valueShapley valueA feature's average contribution to a prediction, over all orders in which features could arrive. comes from game theory. Imagine features arriving one by one, each adding whatever it adds to the prediction at that moment. A feature's share is its average contribution across all arrival orders.

ϕj=1∣F∣!∑orders[f(S∪{j})−f(S)]\phi_j = \frac{1}{|F|!}\sum_{\text{orders}} \big[f(S \cup \{j\}) - f(S)\big]

The shares add up exactly to the gap. No other method of division meets the same fairness rules.

02

Why average over orders?

Predict

Predict first

The model is x1×x2x_1 \times x_2, and absent features are set to 0. Row: x1=2x_1 = 2, x2=1x_2 = 1. If x1x_1 arrives first, what does each feature's arrival add?

They both get halfThe one that arrives second gets everythingThe one that arrives first gets everything
Reveal

The second arrival gets everything. x1x_1 alone gives 2×0=02 \times 0 = 0. Then x2x_2 adds all of 2. In the other order, x1x_1 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.

03

Build one

Explore

Change 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 x1x_1 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?

0.0
How sure?

Model

2.0
1.0
1.0
0.0

Order features arrive

f = 3x₁x₂ + x₃

1. x₁ arrives+0.002. x₂ arrives+6.003. x₃ arrives+1.003.00x₁: 3.00order: 0.003.00x₂: 3.00order: 6.001.00x₃: 1.00order: 1.00

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 first; the figure appears when you commit.

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.

  1. 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_star against base_zero in phi_zero.

    Show a solution
    Python
    def 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)
    R
    shapley <- 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)
  2. Do they add up?

    Shapley values are efficient: they add up to f(x) − f(base). Store True (R: TRUE) in adds_up if the sum of phi_zero is within 1e-9 of f(x_star) − f(base_zero), else False.

    Show a solution
    Python
    adds_up = bool(abs(phi_zero.sum() - (f(x_star) - f(base_zero))) < 1e-9)
    R
    adds_up <- abs(sum(phi_zero) - (f(x_star) - f(base_zero))) < 1e-9
  3. Change the baseline

    Store the Shapley values of the same prediction against base_mean in phi_mean. Which feature's attribution changes sign or size the most?

    Show a solution
    Python
    phi_mean = shapley(x_star, base_mean)
    R
    phi_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.

04

Exact, or estimated?

Read

Trying 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.

05

Read the charts

Explore

Each 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.

SHAP beeswarmHow does each feature push individual predictions up or down, and for which values?
View data
featureSHAP value (log-odds)feature value (rank-scaled)
glucose0.25010.6740
BMI0.12630.4910
age0.08840.6480
pedigree−0.30250.0370
pregnancies0.07700.5690
blood pressure−0.10490.1230
glucose0.33180.6080
BMI−0.74290.0030
age0.27390.6810
pedigree0.23840.7150
pregnancies−0.24390.0260
blood pressure−0.03160.3600
glucose−0.85820.1400
BMI−0.38090.2200
age−0.23960.2930
pedigree0.08420.6400
pregnancies−0.17160.0910
blood pressure−0.10110.0460
glucose−0.37190.4570
BMI0.02420.5250
age0.12980.5910
pedigree−0.25820.1220
pregnancies0.06670.6390
blood pressure0.11710.9120
glucose0.69980.8470
BMI0.72280.9990
age−0.54050.0410
pedigree0.23890.7990
pregnancies−0.15290.1120
blood pressure0.00830.6030
glucose−0.99550.0140
BMI0.51940.8710
age0.21680.6570
pedigree−0.26190.1260
pregnancies−0.21930.1420
blood pressure0.13410.9780
glucose−0.16170.3690
BMI−0.03340.4970
age0.36670.9080
pedigree0.30550.9370
pregnancies−0.19950.1390
blood pressure0.04390.6410
glucose0.60850.8140
BMI0.58470.8280
age0.43000.8090
pedigree−0.27830.0600
pregnancies0.12660.7150
blood pressure−0.10540.1620
glucose0.62490.7950
BMI−0.30030.3550
age−0.52180.0940
pedigree−0.26070.0510
pregnancies0.18970.9090
blood pressure−0.07930.0940
glucose0.09000.5890
BMI0.64760.9720
age−0.01680.3380
pedigree0.33540.8950
pregnancies0.16040.7980
blood pressure0.03530.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.

SHAP waterfallWhy did the model make this particular prediction?
View data
featureSHAP value (log-odds)value
glucose1.222168
BMI0.565038.2
age0.346051
pedigree−0.27400.21
pregnancies0.11403
blood pressure−0.063074
4 other features0.0630—
06

Not a cause

Read

SHAP 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.

07

Check your understanding

Checkpoint

Check yourself

Base value 0.30. Contributions: glucose +0.20+0.20, BMI −0.10-0.10, 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: 0.55−0.30=0.250.55 - 0.30 = 0.25, so age is 0.25−0.20+0.10=0.150.25 - 0.20 + 0.10 = 0.15.

Check yourself

The model never reads x3x_3. What is x3x_3'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.

08

Explain a run

In the app

In 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.

Python
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))
R
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)
09

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