Shapley values and SHAP
Ground local additive explanations in cooperative game theory, prove Shapley value uniqueness and examine interventional versus observational value functions. Implement exact calculation, permutation sampling and KernelSHAP; study TreeSHAP, interactions and limitations.
After this lesson you can
- Prove uniqueness of the Shapley value from efficiency, symmetry, null player and additivity.
- Derive and implement KernelSHAP as weighted regression with the Shapley kernel.
- Explain interventional versus observational SHAP and choose according to the question.
- Describe TreeSHAP and use it on tree ensembles.
- Calculate interaction values and build global summaries without confusing them with causal effects.
Before you start
Allocating a difference
A prediction is above a reference value. How much belongs to each feature? If two features act together, adding one before or after the other gives different answers. The Shapley value averages those contributions over all orderings. It is a precise rule for a given game; it does not itself choose the appropriate game or turn the allocation into a causal explanation.
The empty value is zero and the full coalition value is 5.5. In each order differences telescope and sum to 5.5, but the interaction 3 falls to the second of the two involved features. In half the orders it is the first feature and in the other half the second: mean attributions are . This is a property of this game, not a measurement of real data.
Four axioms and one rule
A cooperative game of players is a function , with and . The Shapley value assigns each player
The coefficient is the probability that exactly precedes in a uniform permutation: there are orders before and after. It therefore equals averaging the increment of over the permutations. It satisfies efficiency , symmetry for interchangeable players, null player if the value never changes and additivity . Efficiency follows from telescoping each order; the other three are read directly from the formula.
Proof
For each nonempty set , define the unanimity game if and zero otherwise. Players outside are null. Those in are symmetric, and efficiency forces for each. The rule is determined on each .
Every game has expansion , with . Indeed, the coefficient of in is , equal to one if and zero otherwise. Additivity implies rational homogeneity; for reals it follows directly without assuming continuity by applying symmetry and efficiency to scaled game , then finite additivity. Thus the rule is unique on the basis and therefore every game. The permutation formula satisfies the axioms, so it is that rule.
∎Which game allocates a prediction
To explain , choose a reference distribution and define a coalition function. The interventional or observational game often takes these forms:
Subtract to apply the normalized game. If the full coalition fixes all features, . The first combines known coordinates with the joint marginal of unknown coordinates; it can create out-of-support inputs. The second asks what the model predicts when is observed and depends on estimating a conditional distribution. Neither is automatically an effect of the causal intervention operator. Chen et al. discuss choosing according to whether the goal is reflecting the function or statistical information in data.
In the example, , , and in the observational game. Therefore and . For the marginal game, and the allocation is . The sum agrees, but the meanings differ. If the linear predictor is and the reference has means , the marginal game gives exactly , even if reference features are correlated.
To show this, substitute coordinates of : . Adding removes and adds , independently of . Averaging over orders leaves that difference intact. Correlation among unknown features can matter for a nonlinear predictor even though it does not change this linear identity. Also, “interventional” here names marginal replacement of predictor inputs: no structural model has been specified describing how other variables would react to a physical intervention.
The baseline is also a choice. If background represents clients accepted in another period, and attributions for the same application can change even if and do not. A small set introduces sample variation; one contaminated by post-decision information answers a different question. Document background composition, date, size and preprocessing, and compare justified alternatives. For categorical variables expanded into indicators, an arbitrary coalition can activate incompatible categories: grouping the original variable changes the players and therefore the allocation.
KernelSHAP: constrained regression
KernelSHAP fits an additive explanation to coalition values . Empty and full coalitions impose and . For the others it minimizes
The formula comes from Lundberg and Lee. At endpoints the kernel is interpreted as infinite weight, or more stably as the two exact constraints above. To understand the weight, there are coalitions of size : total weight for a size is proportional to , giving more attention to sizes near the endpoints. With all coalitions this constrained problem returns Shapley values; with a sample it is an estimate subject to sampling choice and design-matrix rank.
One can check why the kernel works on the unanimity basis. For with , problem symmetry forces coefficients for each player in and for others. The full constraint gives . The normal condition in the direction adding one to an inside coefficient and subtracting one from an outside coefficient gives , where, with the weight of a coalition of size ,
The first summand counts coalitions containing the inside player and not the outside one; the second counts those also containing all of . Substituting the kernel makes each summand of equal , so . Identity gives . Therefore and, by efficiency, , : exactly Shapley on . For , symmetry and efficiency give to all. The solution is linear in game values, so expansion into unanimity games extends the result to any game. This derivation explains weight choice; it does not ensure an incomplete sample has rank or that a background is appropriate.
The graph’s sample is a deterministic permutation without replacement of intermediate coalitions. The game sums individual terms, a pair worth 3 and a triple interaction worth 0.75. A particular error sequence can rise as coalitions are added; monotonic convergence is not promised. Including all reproduces the exact allocation. In real estimation, repeat seeds and show uncertainty, especially when is large.
Constraints are also needed to interpret the result numerically. Regression without them can fit intermediate coalitions well yet fail to reconstruct the prediction-background difference. In the laboratory we eliminate the last unknown using and solve for the other . If resulting rows do not span those directions, infinitely many solutions exist and estimation is rejected. Using a pseudoinverse without disclosure would select one, but not supply missing information.
TreeSHAP and interactions
In a tree, a coalition decides which branches an observation follows: at splits on present features follow its branch; for absent features combine branches with reference weights. The TreeSHAP algorithm avoids enumerating every coalition by maintaining presence and absence fractions and weights aggregated by subset size on each path. Lundberg et al. describe the polynomial calculation and extension to interactions. Path coverages are a specific reference distribution, not necessarily the true conditional distribution; interventional mode uses an explicit background set.
The figure enumerates coalitions and propagates fractions to make quantities visible; it does not implement TreeSHAP’s dynamic optimization. Leaves, in binary order with x1 as least significant bit, have values ; explained input is . Coverage is per absent feature and zero for branches incompatible with a present feature. Combining tree models sums their attributions by additivity, always on the same output scale and with the same game.
A real path can query the same feature several times. Treating those queries as distinct players breaks the feature game: the same feature must enter the coalition once and its joint constraints must be respected along the path. The dynamic implementation tracks the path to avoid counting that feature twice. Coverage fractions should not be interpreted as individual probabilities: they describe samples or weights reaching nodes during fitting and can vary across trees. In XGBoost binary classification, summing margin attributions and then applying the logistic function reconstructs probability; applying logistic separately to each attribution and summing does not.
Shapley interaction values between average the second-order difference
over with weights . The matrix is symmetric and its diagonal is defined so each row sums to . By that convention each off-diagonal interaction appears twice in the total sum. Global summaries such as measure mean magnitude over a population: they lose sign and can hide opposing groups. A dependence plot retains individual values but does not turn association into cause.
For example, with two independent zero-mean inputs and at , the marginal game is zero except at the full coalition, where it is one. Each ordinary value is . The only second-order difference is one, so the off-diagonal interaction is in each position and diagonals are zero. The sum of the four matrix entries is one, the difference from baseline. This convention does not mean two distinct interactions: it is the same pair represented symmetrically.
Laboratory from scratch
We use an explicit background set and a function accepting row matrices. Enumeration costs coalition evaluations; with ten features there are 1024, so the example limits background size. The Gaussian conditional requires positive definite covariance in every submatrix used. The linear test allows its conditional expectation to be calculated exactly, without sampling.
import numpy as np
from math import factorial, comb
from itertools import permutations
def value_marginal(f, x, background, mask):
rows = background.copy()
for j in range(len(x)):
if mask & (1 << j): rows[:, j] = x[j]
return float(np.mean(f(rows)))
def shapley_exact(v, m):
values = np.array([v(mask) for mask in range(1 << m)])
phi = np.zeros(m)
for j in range(m):
for mask in range(1 << m):
if mask & (1 << j): continue
s = mask.bit_count()
weight = factorial(s)*factorial(m-s-1)/factorial(m)
phi[j] += weight * (values[mask | (1 << j)]-values[mask])
return values[0], phi
rng = np.random.default_rng(42)
background = rng.normal(size=(32, 10))
w = np.arange(1, 11) / 10
x = np.linspace(-1, 1, 10)
f = lambda X: 0.3 + X @ w
v = lambda mask: value_marginal(f, x, background, mask)
base, exact = shapley_exact(v, 10)
closed = w*(x-background.mean(axis=0))
print('variables:', len(exact), 'coaliciones:', 2**10)
print('error máximo frente a forma cerrada:', float(np.max(np.abs(exact-closed))))
print('eficiencia:', np.isclose(base+exact.sum(), f(x[None, :])[0]))def gaussian_linear_value(mask, x, mu, cov, w, intercept=0.):
known = [j for j in range(len(x)) if mask & (1 << j)]
unknown = [j for j in range(len(x)) if not mask & (1 << j)]
conditional = mu.copy()
conditional[known] = x[known]
if known and unknown:
conditional[unknown] += cov[np.ix_(unknown,known)] @ np.linalg.solve(
cov[np.ix_(known,known)], x[known]-mu[known])
return intercept + w @ conditional
mu = np.zeros(2); cov = np.array([[1., .8], [.8, 1.]])
vg = lambda mask: gaussian_linear_value(mask, np.ones(2), mu, cov, np.array([1.,0.]))
b, ph = shapley_exact(vg, 2)
print('juego condicional:', [round(vg(i), 3) for i in range(4)])
print('reparto observacional:', np.round(ph, 3))The same routine accepts ten features. This equicorrelated covariance is positive definite: its eigenvalues are with multiplicity nine and once, and we take . The observational explanation can assign values to coordinates whose coefficient is zero because they inform about those used. Efficiency is still checked against the mean and prediction.
mu10 = np.zeros(10)
cov10 = .7*np.eye(10)+.3*np.ones((10,10))
w10 = np.zeros(10); w10[:2] = [1., -0.5]
x10 = np.linspace(-1,1,10)
v10 = lambda mask: gaussian_linear_value(mask, x10, mu10, cov10, w10)
b10,p10 = shapley_exact(v10, 10)
print('coaliciones:',2**10,'eficiencia:',np.isclose(b10+p10.sum(),w10@x10))
print('atribuciones a variables no usadas:',np.round(p10[2:],4))For a nonlinear model one may sample the conditional normal. The conditional covariance matrix is the Schur complement. We fix one seed per coalition so repeated queries define the same approximate game: otherwise different orders would compare different random evaluations and noise would be confused with marginal contribution. That estimated game retains Monte Carlo error; reproducibility does not equal accuracy.
def gaussian_mc_value(f, x, mu, cov, mask, draws=64, seed=81):
m = len(x)
known = [j for j in range(m) if mask & (1 << j)]
missing = [j for j in range(m) if not mask & (1 << j)]
if not missing: return float(f(x[None,:])[0])
mean = mu[missing].copy(); conditional_cov = cov[np.ix_(missing,missing)].copy()
if known:
Cuk = cov[np.ix_(missing,known)]; Ckk = cov[np.ix_(known,known)]
mean += Cuk @ np.linalg.solve(Ckk,x[known]-mu[known])
conditional_cov -= Cuk @ np.linalg.solve(Ckk,Cuk.T)
random = np.random.default_rng(seed+mask)
samples = random.multivariate_normal(mean,conditional_cov,size=draws)
rows = np.tile(x,(draws,1)); rows[:,missing] = samples
return float(np.mean(f(rows)))
xn=np.array([1.,-1.,.5,2.]); mun=np.zeros(4); cn=.7*np.eye(4)+.3*np.ones((4,4))
fn=lambda X: X[:,0]*X[:,1]+np.sin(X[:,2])+X[:,3]**2
vn=lambda mask: gaussian_mc_value(fn,xn,mun,cn,mask)
bn,pn=shapley_exact(vn,4)
print('SHAP condicional aproximado:',np.round(pn,4))
print('eficiencia respecto al juego aproximado:',np.isclose(bn+pn.sum(),fn(xn[None,:])[0]))def sample_shapley(v, m, pairs=100, seed=8):
random = np.random.default_rng(seed)
all_values = []
for _ in range(pairs):
order = random.permutation(m)
for path in (order, order[::-1]):
mask = 0; previous = v(mask); contributions = np.zeros(m)
for j in path:
mask |= 1 << int(j)
current = v(mask); contributions[j] = current-previous; previous = current
all_values.append(contributions)
return np.asarray(all_values)
def toy(mask):
return sum([1.,2.,-1.,.5][j] for j in range(4) if mask & (1 << j)) + (3 if mask & 3 == 3 else 0)
samples = sample_shapley(toy, 4, pairs=100)
_, truth = shapley_exact(toy, 4)
print('estimación:', np.round(samples.mean(axis=0), 3), 'exacta:', truth)
print('suma de cada recorrido:', np.unique(samples.sum(axis=1)))Paired trajectories are not independent of each other. For a Monte Carlo interval, first average the two members of each pair and calculate variability between pairs, not among 200 trajectories as if independent. Antithetic sampling can reduce variance in some games, but does not guarantee it for all.
The previous game has only one two-feature interaction: reversing an order changes who receives it, so every antithetic pair already splits it exactly. To study a nontrivial problem, we add a three-feature interaction. Each line uses different seeds and reports the median and maximum of per-repetition maximum errors. Do not expect every individual run to improve as budget increases.
def toy_triple(mask):
return toy(mask) + (.75 if mask & 14 == 14 else 0.)
_, true3 = shapley_exact(toy_triple,4)
for pairs in (4,16,64):
errors = []
for seed in range(12):
est = sample_shapley(toy_triple,4,pairs=pairs,seed=seed).mean(axis=0)
errors.append(np.max(np.abs(est-true3)))
print('pares',pairs,'mediana',round(float(np.median(errors)),4),
'máximo',round(float(np.max(errors)),4))def kernel_shap_values(v, m, masks):
if m < 2: return np.array([v(1)-v(0)])
base, total = v(0), v((1 << m)-1)-v(0)
Z = np.array([[(mask >> j) & 1 for j in range(m)] for mask in masks], dtype=float)
sizes = Z.sum(axis=1).astype(int)
if np.any((sizes == 0) | (sizes == m)): raise ValueError('No incluir extremos')
weights = np.array([(m-1)/(comb(m,s)*s*(m-s)) for s in sizes])
A = Z[:,:-1]-Z[:,-1,None]
y = np.array([v(mask)-base for mask in masks])-Z[:,-1]*total
Aw = A*np.sqrt(weights[:,None]); yw = y*np.sqrt(weights)
if np.linalg.matrix_rank(Aw) < m-1: raise ValueError('Matriz sin rango')
first = np.linalg.lstsq(Aw,yw,rcond=None)[0]
return np.r_[first,total-first.sum()]
m = 4
all_masks = list(range(1, 2**m-1))
k = kernel_shap_values(toy, m, all_masks)
print('Kernel con todas:', np.round(k, 8), 'máximo error:', np.max(np.abs(k-truth)))_, target = shapley_exact(toy_triple,4)
random = np.random.default_rng(17)
order = random.permutation(np.arange(1,15))
for budget in (4,8,14):
try:
estimate = kernel_shap_values(toy_triple,4,order[:budget])
print('coaliciones',budget,'error máximo',round(float(np.max(np.abs(estimate-target))),5))
except ValueError:
print('coaliciones',budget,'diseño sin rango')TreeExplainer on credit
The local comparison uses the UCI dataset from the previous lesson, with the same split and warning about encoded categorical variables. We explain the model’s raw margin, not its probability: summing logits and summing probabilities are different operations. The two TreeExplainer versions have different references and should not be compared as if estimating the same game. The background set is a sample of training, never test labels.
import hashlib, io, urllib.request, zipfile
import numpy as np, pandas as pd, xgboost as xgb, shap
import matplotlib.pyplot as plt
from sklearn.model_selection import train_test_split
from sklearn.metrics import roc_auc_score
url = 'https://archive.ics.uci.edu/static/public/350/default+of+credit+card+clients.zip'
raw = urllib.request.urlopen(url, timeout=120).read()
assert hashlib.sha256(raw).hexdigest() == '56c885f84457f6680f8438f02bfcdac9579323d8a94465ee5f26e32baa727602'
with zipfile.ZipFile(io.BytesIO(raw)) as z:
table = pd.read_excel(io.BytesIO(z.read('default of credit card clients.xls')), header=1)
X = table.drop(columns=['ID','default payment next month'])
y = table['default payment next month'].to_numpy(dtype=int)
Xtr,Xte,ytr,yte = train_test_split(X,y,test_size=.3,stratify=y,random_state=17)
model = xgb.XGBClassifier(n_estimators=120,max_depth=3,learning_rate=.08,
random_state=17,n_jobs=1).fit(Xtr,ytr)
print('AUC de prueba:', round(roc_auc_score(yte,model.predict_proba(Xte)[:,1]),4))
bg = Xtr.sample(n=100,random_state=17)
cases = Xte.iloc[:200]
path = shap.TreeExplainer(model,feature_perturbation='tree_path_dependent',model_output='raw')
inter = shap.TreeExplainer(model,data=bg,feature_perturbation='interventional',model_output='raw')
sp = path.shap_values(cases); si = inter.shap_values(cases)
margin = model.get_booster().predict(xgb.DMatrix(cases), output_margin=True)
print('Error aditivo caminos:',np.max(np.abs(path.expected_value+sp.sum(axis=1)-margin)))
print('Error aditivo intervencional:',np.max(np.abs(inter.expected_value+si.sum(axis=1)-margin)))
print('Diferencia media absoluta de atribuciones:',np.mean(np.abs(sp-si)))npm run lab and open the connection link.small = xgb.XGBClassifier(n_estimators=40,max_depth=3,random_state=17,n_jobs=1).fit(Xtr.iloc[:,:3],ytr)
bg3 = bg.iloc[:,:3]
row = cases.iloc[0,:3].to_numpy()
def marginal_small(mask):
rows = bg3.copy()
for j in range(3):
if mask & (1 << j): rows.iloc[:,j] = row[j]
return float(small.get_booster().predict(xgb.DMatrix(rows), output_margin=True).mean())
from math import factorial
def exact_local(v,m):
out=np.zeros(m)
for j in range(m):
for s in range(1 << m):
if s & (1 << j): continue
k=s.bit_count(); out[j]+=factorial(k)*factorial(m-k-1)/factorial(m)*(v(s|(1<<j))-v(s))
return out
own = exact_local(marginal_small,3)
explainer3 = shap.TreeExplainer(small,data=bg3,feature_perturbation='interventional',model_output='raw')
library = explainer3.shap_values(cases.iloc[:1,:3])[0]
print('Atribuciones propias:',np.round(own,5),'biblioteca:',np.round(library,5))
print('Diferencia máxima:',np.max(np.abs(own-library)))npm run lab and open the connection link.interaction = path.shap_interaction_values(cases.iloc[:30])
print('forma matriz interacciones:',interaction.shape)
print('error filas frente a SHAP:',np.max(np.abs(interaction.sum(axis=2)-sp[:30])))
shap.summary_plot(si,cases,show=False); plt.tight_layout(); plt.show()
shap.dependence_plot(0,si,cases,show=False); plt.tight_layout(); plt.show()npm run lab and open the connection link.The enumeration comparison uses three features and all their coalitions, while the full ensemble explanation uses all 23 columns. Interaction is calculated in path mode and must not be confused with an interventional interaction for which the implementation may not offer that calculation. The plots show this particular model, background and sample. Changing any changes the explanation.
Covert, Lundberg and Lee group feature-removal explanation methods by three choices: how information is removed, what behavior is explained and how contributions are summarized. The framework helps compare SHAP with permutation or LIME without assuming the same feature name means the same question. The next lesson revisits that comparison with local surrogates and counterfactuals.
Exercises
Step 1 of 3. What do players outside T receive?
import numpy as np
def kernel_shap(f, x, background, n_samples):
passSummary
- Permutation averaging and the subset formula are equivalent; joint terms are allocated according to marginal contributions.
- KernelSHAP approximates a weighted fit with efficiency imposed. TreeSHAP exploits tree structure, but its modes use different references.
- Interactions and mean absolute values describe the predictor on a given population and scale; they do not identify causal effects.