Module contents
Lesson 9 of 39Core 110 min

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.

InteractiveFeatures enter in order
−1012345x11x25x3−1x40.5
1
4
Orderx1 → x2 → x3 → x4
Current value5.50
Exact average(2.5, 3.5, −1, 0.5)
The game has individual contributions (1, 2, −1, 0.5) and an extra term of 3 when x1 and x2 are present. Change the order and step through it: averaging all 24 orders splits the joint term equally.

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 (2.5,3.5,−1,0.5)(2.5,3.5,-1,0.5). This is a property of this game, not a measurement of real data.

Four axioms and one rule

A cooperative game of MM players is a function v:2N→Rv:2^N\to\R, with N={1,…,M}N=\{1,\dots,M\} and v(∅)=0v(\varnothing)=0. The Shapley value assigns each player

ϕj(v)=∑S⊆N∖{j}∣S∣!(M−∣S∣−1)!M! [v(S∪{j})−v(S)].\phi_j(v)=\sum_{S\subseteq N\setminus\{j\}}\frac{|S|!(M-|S|-1)!}{M!}\,[v(S\cup\{j\})-v(S)].

The coefficient is the probability that exactly SS precedes jj in a uniform permutation: there are ∣S∣!|S|! orders before and (M−∣S∣−1)!(M-|S|-1)! after. It therefore equals averaging the increment of jj over the M!M! permutations. It satisfies efficiency ∑jϕj=v(N)\sum_j\phi_j=v(N), symmetry for interchangeable players, null player if the value never changes and additivity ϕ(v+w)=ϕ(v)+ϕ(w)\phi(v+w)=\phi(v)+\phi(w). Efficiency follows from telescoping each order; the other three are read directly from the formula.

Proof

For each nonempty set TT, define the unanimity game uT(S)=1u_T(S)=1 if T⊆ST\subseteq S and zero otherwise. Players outside TT are null. Those in TT are symmetric, and efficiency forces 1/∣T∣1/|T| for each. The rule is determined on each uTu_T.

Every game has expansion v=∑T≠∅aTuTv=\sum_{T\ne\varnothing} a_T u_T, with aT=∑S⊆T(−1)∣T∣−∣S∣v(S)a_T=\sum_{S\subseteq T}(-1)^{|T|-|S|}v(S). Indeed, the coefficient of v(S)v(S) in ∑T⊆UaT\sum_{T\subseteq U}a_T is ∑S⊆T⊆U(−1)∣T∣−∣S∣\sum_{S\subseteq T\subseteq U}(-1)^{|T|-|S|}, equal to one if S=US=U and zero otherwise. Additivity implies rational homogeneity; for reals it follows directly without assuming continuity by applying symmetry and efficiency to scaled game aTuTa_Tu_T, 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 f(x)f(x), choose a reference distribution and define a coalition function. The interventional or observational game often takes these forms:

vint(S)=EX−Sf(xS,X−S),vobs(S)=E[f(X)∣XS=xS].v_{\mathrm{int}}(S)=\E_{X_{-S}}f(x_S,X_{-S}),\qquad v_{\mathrm{obs}}(S)=\E[f(X)\mid X_S=x_S].

Subtract v(∅)v(\varnothing) to apply the normalized game. If the full coalition fixes all features, f(x)=v(∅)+∑jϕjf(x)=v(\varnothing)+\sum_j\phi_j. 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 XS=xSX_S=x_S 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.

InteractiveFaithful to model or data
00.20.40.60.81x1 marginal1x2 marginal0x1 cond.0.6x2 cond.0.4
0.8
Interventional(1, 0)
Observational(0.60, 0.40)
With standard bivariate normal X, f(x)=x1 and observation x=(1,1), the conditional game attributes part to x2 according to correlation. The marginal game assigns zero to a variable f does not use.

In the example, v(∅)=0v(\varnothing)=0, v({1})=1v(\{1\})=1, v({2})=ρv(\{2\})=\rho and v({1,2})=1v(\{1,2\})=1 in the observational game. Therefore ϕ1=1−ρ/2\phi_1=1-\rho/2 and ϕ2=ρ/2\phi_2=\rho/2. For the marginal game, v({2})=0v(\{2\})=0 and the allocation is (1,0)(1,0). The sum agrees, but the meanings differ. If the linear predictor is f(x)=b+∑jwjxjf(x)=b+\sum_jw_jx_j and the reference has means μj\mu_j, the marginal game gives exactly ϕj=wj(xj−μj)\phi_j=w_j(x_j-\mu_j), even if reference features are correlated.

To show this, substitute coordinates of SS: vint(S)=b+∑j∈Swjxj+∑j∉Swjμjv_{\rm int}(S)=b+\sum_{j\in S}w_jx_j+\sum_{j\notin S}w_j\mu_j. Adding jj removes wjμjw_j\mu_j and adds wjxjw_jx_j, independently of SS. 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, Ef(X)\E f(X) and attributions for the same application can change even if ff and xx 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 g(z)=ϕ0+∑jϕjzjg(z)=\phi_0+\sum_j\phi_jz_j to coalition values z∈{0,1}Mz\in\{0,1\}^M. Empty and full coalitions impose ϕ0=v(∅)\phi_0=v(\varnothing) and ∑jϕj=v(N)−v(∅)\sum_j\phi_j=v(N)-v(\varnothing). For the others it minimizes

∑z:0<∣z∣<MM−1(M∣z∣)∣z∣(M−∣z∣) [v(z)−ϕ0−z⊤ϕ]2.\sum_{z:0<|z|<M}\frac{M-1}{\binom{M}{|z|}|z|(M-|z|)}\,[v(z)-\phi_0-z\T\vb{\phi}]^2.

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 (Ms)\binom{M}{s} coalitions of size ss: total weight for a size is proportional to 1/[s(M−s)]1/[s(M-s)], 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 uTu_T with t=∣T∣<Mt=|T|<M, problem symmetry forces coefficients aa for each player in TT and bb for others. The full constraint gives ta+(M−t)b=1ta+(M-t)b=1. The normal condition in the direction adding one to an inside coefficient and subtracting one from an outside coefficient gives (a−b)C=A(a-b)C=A, where, with wsw_s the weight of a coalition of size ss,

C=∑s=1M−1(M−2s−1)ws,A=∑s=tM−1(M−t−1s−t)ws.C=\sum_{s=1}^{M-1}\binom{M-2}{s-1}w_s,\qquad A=\sum_{s=t}^{M-1}\binom{M-t-1}{s-t}w_s.

The first summand counts coalitions containing the inside player and not the outside one; the second counts those also containing all of TT. Substituting the kernel makes each summand of CC equal 1/M1/M, so C=(M−1)/MC=(M-1)/M. Identity ∑s=tM−1(s−1t−1)=(M−1t)\sum_{s=t}^{M-1}\binom{s-1}{t-1}=\binom{M-1}{t} gives A=(M−1)/(Mt)A=(M-1)/(Mt). Therefore a−b=1/ta-b=1/t and, by efficiency, a=1/ta=1/t, b=0b=0: exactly Shapley on uTu_T. For t=Mt=M, symmetry and efficiency give 1/M1/M 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.

InteractiveThe weight of each coalition
00.050.10.150.20.2510.2520.12530.25
4
8
Maximum error1.200
Total available14
Change feature count and budget. The graph shows weight of each coalition of a size, and the readout compares constrained regression with the exact result of the explicit game; an insufficient-rank sample has no unique solution.

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 MM 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 ϕM=v(N)−v(∅)−∑j<Mϕj\phi_M=v(N)-v(\varnothing)-\sum_{j<M}\phi_j and solve for the other M−1M-1. 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.

InteractiveCoverage and coalitions in a tree
0.000.020.040.060.080.100.120.1400.1310.1320.1330.1340.1350.1360.1370.13
x1
0
0
Coalitionempty
Leaf fraction0.125
Coalition weight0.333
Marginal contribution0.625
Exact Shapley0.583
A complete three-level tree uses a distinct feature per level, with equiprobable branches. Choose a feature and one of four preceding coalitions, and traverse leaves. Bars show coverage fractions; readouts give combinatorial weight, increment and exact average.

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 (−1,0,1,2,3,4,5,7)(-1,0,1,2,3,4,5,7); explained input is (1,0,1)(1,0,1). Coverage is 1/21/2 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 i≠ji\ne j average the second-order difference

Δijv(S)=v(S∪{i,j})−v(S∪{i})−v(S∪{j})+v(S)\Delta_{ij}v(S)=v(S\cup\{i,j\})-v(S\cup\{i\})-v(S\cup\{j\})+v(S)

over S⊆N∖{i,j}S\subseteq N\setminus\{i,j\} with weights ∣S∣!(M−∣S∣−2)!/[2(M−1)!]|S|!(M-|S|-2)!/[2(M-1)!]. The matrix is symmetric and its diagonal is defined so each row sums to ϕi\phi_i. By that convention each off-diagonal interaction appears twice in the total sum. Global summaries such as E∣ϕj∣\E|\phi_j| 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 f(x)=x1x2f(x)=x_1x_2 at x=(1,1)x=(1,1), the marginal game is zero except at the full coalition, where it is one. Each ordinary value is 1/21/2. The only second-order difference is one, so the off-diagonal interaction is 1/21/2 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 2M2^M 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.

[ ]Marginal game and exact ShapleyBrowser
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]))
[ ]Gaussian conditional expectation for linear fBrowser
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 1−ρ1-\rho with multiplicity nine and 1+9ρ1+9\rho once, and we take ρ=0.3\rho=0.3. 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.

[ ]Ten-feature conditional gameBrowser
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.

[ ]Conditional value function for a nonlinear modelBrowser
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]))
[ ]Antithetic permutationsBrowser
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.

[ ]Convergence with a triple interactionBrowser
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))
[ ]KernelSHAP with exact constraintBrowser
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)))
[ ]Coalition budgetBrowser
_, 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.

[ ]XGBoost and two TreeSHAP gamesLocal GPU
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)))
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.
[ ]Custom enumeration versus TreeExplainerLocal GPU
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)))
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.
[ ]Interactions and summariesLocal GPU
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()
This cell needs the local lab (PyTorch with your GPU). Start it with 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

Proof
Prove: The four axioms determine the Shapley value for finite games.
0
Use unanimity games u_T and inclusion-exclusion expansion.

Step 1 of 3. What do players outside T receive?

Numeric
A three-player game has v(empty)=0, v(1)=1, v(2)=2, v(3)=0, v(12)=5, v(13)=1, v(23)=2 and v(123)=5. What is player 1’s Shapley value?
Numeric
For f(x)=2x1−x2, background means (1,0) and x=(3,2), what is marginal SHAP value of x1?
Quiz
The predictor uses x1 and not x2, a correlated copy. What can happen when explaining an observation?
CodeKernelSHAP for a finite background
Implement kernel_shap(f, x, background, n_samples). Enumerate intermediate coalitions in ascending order up to n_samples, evaluate mean predictor output when absent features are replaced by background rows, and solve weighted least squares subject to efficiency. If the design lacks rank, raise ValueError. Tests provide sufficient budget.
import numpy as np
def kernel_shap(f, x, background, n_samples):
  pass
Shift+Enter to run

Summary

Key idea
Shapley uniquely allocates a coalition game under four axioms; choice of game and background remains a substantive decision.
  • 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.