Sub topic 4
Additivity: Prediction = Baseline + Sum of SHAP Values
SHAP values are built so that they add up exactly to the prediction being explained. This chapter covers that property, how to verify it in code, and what it means when the check fails.
Prerequisites
This chapter assumes you can:
- Train and call
predicton a scikit-learn style model. - Use pandas DataFrames and NumPy arrays.
- Read the idea of a Shapley value from the earlier chapters: a feature's average marginal contribution over all orders in which features can be added.
You should also know that the baseline is the model's average output over a background dataset, covered in the previous chapter.
The additivity equation
For one row x, SHAP produces one number per feature, written φ₁ … φₙ, and a baseline φ₀. They satisfy:
f(x) = φ₀ + φ₁ + φ₂ + ... + φₙHere f(x) is the model output being explained and φ₀ is the baseline. Rearranged, the sum of the SHAP values equals f(x) - φ₀. That is the gap between this prediction and the average prediction.
This property has two names:
- Local accuracy. The explanation reproduces the model output for this specific row.
- Efficiency. This is the game-theory name. The "payout"
f(x) - φ₀is fully shared among the "players", the features, with nothing left over.
The word "local" matters. The equation holds row by row, not only on average. Every row gets its own φ values, and each row's values sum to that row's gap from the baseline.
Additivity is what makes SHAP explanations easy to audit. If you can reconstruct the prediction from the pieces, the explanation accounts for everything the model did. A method that gives you only a ranking of features cannot offer that check.
Verifying it with brute force
The function below computes exact Shapley values for a tiny function. It tries every subset of the other features, replaces the features outside the subset with baseline values, and averages the marginal contributions with the Shapley weights.
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.0Work through the numbers:
f(x) = 2*1 + 2*3 = 8andf(baseline) = 0, so the gap to explain is 8.- Feature 0 enters only through
2 * z[0], so it gets exactly 2. - The product
z[1] * z[2]is worth 6 only when both features are present. Neither feature can earn it alone, so the 6 is split equally: 3 each. - 2 + 3 + 3 = 8, which matches the gap.
The equal split of the interaction is a consequence of the Shapley weights, which treat features symmetrically. Additivity holds even though the function is not a simple sum of per-feature terms. Interactions are not lost. They are assigned to the features involved.
Verifying it on a real model
The library exposes the baseline as base_values and the per-feature values as values on the Explanation object. The check below compares them with the model's own predictions for every row.
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) # (442, 10)
reconstructed = sv.base_values + sv.values.sum(axis=1)
print(np.allclose(reconstructed, model.predict(X), atol=1e-4)) # Truesv.values has one row per sample and one column per feature. sv.base_values has one entry per sample. For TreeExplainer these entries are all the same number, because the baseline does not depend on the row being explained.
Built-in additivity check
TreeExplainer runs this same check for you. When you call it, it compares the sum of the SHAP values plus the baseline against the model's output. If the two differ by more than a small tolerance, it raises an error that mentions the additivity check.
You can turn that check off with check_additivity=False:
sv = explainer(X, check_additivity=False)Turning it off hides the symptom without fixing the cause. Use it only after you understand why the numbers differ, for example a known float32 rounding issue in a boosted-tree library.
Using additivity in practice
The equation gives you more than a sanity check.
Comparing two rows
Both rows share the same baseline, so the baseline cancels when you subtract. The difference between two predictions equals the sum of the differences in their SHAP values:
a, b = 0, 1
pred_diff = model.predict(X.iloc[[a]])[0] - model.predict(X.iloc[[b]])[0]
shap_diff = (sv.values[a] - sv.values[b]).sum()
print(np.isclose(pred_diff, shap_diff, atol=1e-3)) # TrueTo explain why row a is predicted higher than row b, look at which features have the largest differences in their values.
Grouping features
Because the contributions add, you can sum the SHAP values of several columns and treat the total as the contribution of the group. This is common for one-hot encoded columns that come from one categorical variable, or for several lagged versions of one measurement. The sum is meaningful because the equation holds for any partition of the features.
Reconstructing from a plot
A waterfall plot is the additivity equation drawn as bars. It starts at the baseline and ends at the prediction. The bars between them are the SHAP values. If the end of the plot does not match the model output you expect, the cause is almost always one of the issues in the next section.
Common errors
| Symptom | Likely cause | Fix |
|---|---|---|
| The sum is far from `predict_proba` | SHAP values are in raw model output units, not probabilities | Compare with `decision_function` or the raw margin, then apply the sigmoid |
| Additivity error raised for XGBoost or LightGBM | Float32 rounding inside the library, or a mismatch between the model and the explainer | Check library versions and refit; use `check_additivity=False` only if the gap is tiny |
| The sum is off by a constant | You compared against the wrong baseline, such as the mean of the labels | Use `sv.base_values`, which is the mean model output on the background |
| Mismatch after retraining | The explainer was built from an older model | Recreate the explainer after every fit |
| Shape errors with multi-class models | There is one baseline and one set of SHAP values per class | Select the class dimension before summing |
Classification example
The units point is the most common source of confusion. A gradient boosting classifier works internally in log-odds, and SHAP explains that raw output.
import numpy as np
import shap
from scipy.special import expit
from sklearn.datasets import load_breast_cancer
from sklearn.ensemble import GradientBoostingClassifier
Xc, yc = load_breast_cancer(return_X_y=True, as_frame=True)
clf = GradientBoostingClassifier(random_state=0).fit(Xc, yc)
svc = shap.TreeExplainer(clf)(Xc)
margin = svc.base_values + svc.values.sum(axis=1)
print(np.allclose(margin, clf.decision_function(Xc), atol=1e-3)) # True
print(np.allclose(expit(margin), clf.predict_proba(Xc)[:, 1], atol=1e-3)) # TrueThe sum is exact in log-odds. The probability is a nonlinear transform of that sum, so you cannot add SHAP values in probability space.
Summary of what to check
When SHAP output looks wrong, run this checklist in order:
- Is the explainer built from the current, fitted model?
- Are you comparing with the same output the explainer used: raw margin, not probability, for most classifiers?
- Are you using
base_valuesfrom theExplanation, not a baseline you computed yourself? - Are you selecting the right class for multi-class models?
- Is the additivity check still enabled?
Exercises
Exercise
A GradientBoostingClassifier predicts probability 0.88 for a row. The baseline in sv.base_values is 0.2 and the SHAP values sum to 1.5. Is there a contradiction?
Show answer
Not necessarily. The baseline and SHAP values are in log-odds, not probabilities. The raw margin is 0.2 + 1.5 = 1.7, and the sigmoid of 1.7 is about 0.85. That is close to 0.88, and the remaining gap is explained by rounding in the quoted numbers. To verify, add the baseline and the SHAP sum in log-odds, then apply the sigmoid. Never add probabilities and SHAP values directly.
Exercise
For the function f(z) = z[0] * z[1] with x = [3, 4] and baseline [0, 0], what are the Shapley values, and what do they sum to?
Show answer
f(x) = 12 and f(baseline) = 0, so the gap is 12. The product is created only when both features are present, so the interaction is split equally. The values are [6.0, 6.0], which sum to 12 and match f(x) - f(baseline).
Exercise
You compute sv.base_values[0] + sv.values[0].sum() and it differs from model.predict(X.iloc[[0]])[0] by 15. List two possible causes and how you would test each.
Show answer
One cause is that the explainer was built from an older version of the model. Rebuild it from the current model and rerun the check. Another cause is that the explained output differs from the compared output, for example a classifier's log-odds against its probability. Compare against decision_function or the raw margin instead. A third possibility is a wrongly selected class dimension in a multi-class model.