Sub topic 4
Additivity: prediction = baseline + sum of SHAP values
This chapter assumes you can fit a scikit-learn style model, use NumPy and pandas, and have met the Shapley value and baseline ideas from the earlier chapters.
The property
SHAP is an additive feature attribution method. For one row x, the explanation is a baseline value plus one number per feature:
f(x) = baseline + phi_1 + phi_2 + ... + phi_nHere f(x) is the model output for the row. The baseline is the expected model output over the background data. Each phi_i is the SHAP value of feature i for this row. The property is called local accuracy (also efficiency): the contributions add up exactly to the gap between the prediction and the baseline.
Checking it by hand
The brute-force computation below uses a function with an interaction term. The baseline row is all zeros, so f(baseline) is 0.
from itertools import combinations
from math import factorial
def shapley_values(f, x, baseline):
n = len(x)
def value(subset):
z = [x[i] if i in subset else baseline[i] for i in range(n)]
return f(z)
phi = []
for i in range(n):
others = [j for j in range(n) if j != i]
total = 0.0
for size in range(n):
for subset in combinations(others, size):
s = set(subset)
weight = factorial(len(s)) * factorial(n - len(s) - 1) / factorial(n)
total += weight * (value(s | {i}) - value(s))
phi.append(total)
return phi
f = lambda z: 2 * z[0] + z[1] * z[2]
x = [1, 2, 3]
baseline = [0, 0, 0]
phi = shapley_values(f, x, baseline)
print(phi) # [2.0, 3.0, 3.0]
print(sum(phi), f(x) - f(baseline)) # 8.0 8.0Feature 0 enters linearly, so it gets its full term, 2. The product z[1]*z[2] equals 6 and cannot be assigned to one feature alone. The Shapley weights split it equally, so features 1 and 2 each get 3. The total is 8, which is f(x) - f(baseline).
Checking it with the library
With a real model, test the identity per row. Use base_values and values from the Explanation object.
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)
explainer = shap.TreeExplainer(model)
sv = explainer(X)
print(sv.values.shape) # (n_samples, n_features)
print(np.isclose(sv.base_values[0] + sv.values[0].sum(),
model.predict(X.iloc[[0]])[0], atol=1e-4))The check should print True. The tolerance is there because TreeExplainer may compute in floating point with small rounding differences.
Using the identity
- Sanity test. Run the check on a sample of rows after you change models, explainers, or background data. A failure points to a setup problem, not a rare bug.
- Reading signs. A positive
phipushes this prediction above the baseline. A negative one pulls it below. The sizes are in the same units as the model output. - Comparing rows. Two rows differ in prediction only through their baseline-relative contributions, because the baseline is shared.
Common errors
- Comparing in the wrong units. For classifiers, TreeExplainer often explains the raw margin (log-odds), not
predict_proba. Adding the values to the baseline reproduces the margin. Convert it with a sigmoid before comparing it to a probability. - Using the wrong baseline. If you compare against
y.mean()instead ofbase_values, the sum is off. The baseline is the mean model output on the background data, not the mean of the target. - Tolerance too tight. Compare with
np.iscloseand a smallatol, not==. - Expecting a different identity for a subset of features. The identity needs all features. Summing only the plotted top features leaves out the rest.
Exercise
A model's baseline is 20.0 and its prediction for a row is 26.5. The SHAP values for three features are +5.0, +3.0 and phi3. What is phi3, and what does its sign mean?
Show answer
phi_3 = 26.5 - 20.0 - 5.0 - 3.0 = -1.5. The negative sign means this feature pulled the prediction below what the other features alone would give. Its size, 1.5, is in the model's output units.