AI Logic

Explainability (XAI)

SHAP (SHapley Additive exPlanations)

Updated:

Diagram of SHAP. Left: the flow in which the model predicts on each subset of features, and the increase from adding a feature is averaged over all orderings to give the SHAP value. Right: a worked example in which an image of a circle and a triangle is split into three features, showing predictions for the 8 subsets, the increases for each of the 6 orderings and their averages, and how adding the SHAP values to the base value reaches the prediction

What is SHAP?

SHAP (SHapley Additive exPlanations) is a method that splits a single prediction into a sum of per-feature contributions. The contributions are given by Shapley values from cooperative game theory. It was proposed by Lundberg and Lee in 2017.

Shapley values are a way to fairly divide a reward earned by a group of cooperating players according to each player's contribution. SHAP treats features as "players" and the prediction as the "reward." The contribution of a feature (its SHAP value) is how much the prediction changes when that feature is added, averaged over all orders in which features can be added.

SHAP values have two key strengths:

  • Contributions sum to the prediction: Adding all SHAP values to the prediction made when no feature is known (the base value) gives exactly the actual prediction.
  • They are the unique solution satisfying desirable properties: The paper showed that six methods, including LIME, DeepLIFT and LRP, share the same form of explanation, and that Shapley values are the only explanation of that form satisfying three properties.

When three people do a job together and earn a reward, how one person's contribution looks depends on "who arrived first." The first to arrive can make progress alone, while a later arrival might only add a little to work that is already done. Shapley values remove this order-dependent unfairness by trying every arrival order and averaging.

Background: unifying six methods into one form

Before SHAP, it was unclear which prediction explanation method worked best when, or how the methods related to each other. The paper proposed viewing an explanation itself as a simple model that approximates the original model (an explanation model).

The explanation model gg is a linear function of the following form that takes a simplified input z′∈{0,1}Mz' \in \{0, 1\}^M, which indicates whether each feature is "present (1)" or "absent (0)." The paper calls this an additive feature attribution method (Definition 1). MM is the number of simplified features and ϕi\phi_i is the contribution of feature ii.

g(z′)=ϕ0+∑i=1Mϕizi′(1)g(z') = \phi_0 + \sum_{i=1}^{M} \phi_i z'_i \qquad (1)

A simplified input is mapped back to the original input by a mapping hxh_x (x=hx(x′)x = h_x(x')). The paper showed that the following six methods fit this form.

MethodHow an "absent" feature is representedHow contributions are computed
LIMERemove words or superpixels (fill them in for images)Linear regression weighted by proximity
DeepLIFTSet the input to a reference valueBackpropagate differences from the reference layer by layer
LRPSet the input to 0 (equivalent to DeepLIFT with all neuron references set to 0)Backpropagate relevance layer by layer
Shapley regression valuesRetrain the model without the featureRetrain on every subset and compare
Shapley sampling valuesReplace with values from the training data and averageApproximate Eq. 8 by sampling
Quantitative Input Influence (QII)Same as aboveNearly the same approximation as Shapley sampling values

Three properties and SHAP values

The paper requires the following three properties of an explanation of the form in Eq. 1.

  • Local accuracy (Property 1): At the x′x' corresponding to the original input, the explanation model matches the output of the original model: f(x)=g(x′)=ϕ0+∑i=1Mϕixi′f(x) = g(x') = \phi_0 + \sum_{i=1}^{M} \phi_i x'_i.
  • Missingness (Property 2): A feature that is "absent" in the original input (xi′=0x'_i = 0) gets a contribution of 0.
  • Consistency (Property 3): If the model changes so that the increase in output from adding a feature becomes larger or stays the same regardless of which other features are present, that feature's contribution does not decrease.

Only one explanation satisfies all three, and it is the Shapley value (Theorem 1). Here fx(z′)=f(hx(z′))f_x(z') = f(h_x(z')), ∣z′∣|z'| is the number of ones in z′z', and z′∖iz' \setminus i is the input with zi′z'_i set to 0. The sum is over all z′z' whose ones lie in a subset of the positions of the ones in x′x'.

ϕi(f,x)=∑z′⊆x′∣z′∣! (M−∣z′∣−1)!M![fx(z′)−fx(z′∖i)](8)\phi_i(f, x) = \sum_{z' \subseteq x'} \frac{|z'|!\,(M - |z'| - 1)!}{M!} \big[f_x(z') - f_x(z' \setminus i)\big] \qquad (8)

The coefficient ∣z′∣! (M−∣z′∣−1)!M!\frac{|z'|!\,(M - |z'| - 1)!}{M!} is the fraction of all orderings of the MM features in which exactly the features of z′∖iz' \setminus i come before feature ii. Eq. 8 is therefore the same as "adding features one at a time and averaging, over all orderings, the increase when ii is added." From this result, the paper states that methods not based on Shapley values violate either local accuracy or consistency.

SHAP values are Shapley values in which the model output is taken to be a conditional expectation. Many models cannot handle inputs in which features are "absent," so the expectation is taken over the absent features. SS is the set of positions of ones in z′z' and Sˉ\bar{S} is the rest.

fx(z′)=E[f(z)∣zS]≈EzSˉ[f(z)]≈f([zS,E[zSˉ]])f_x(z') = E[f(z) \mid z_S] \approx E_{z_{\bar{S}}}[f(z)] \approx f\big([z_S, E[z_{\bar{S}}]]\big)

The first approximation assumes features are independent (Eq. 11), and the second assumes the model is linear (Eq. 12). The base value ϕ0=fx(∅)\phi_0 = f_x(\varnothing) is the expected prediction E[f(z)]E[f(z)] when no feature is known.

The right side of the diagram at the top shows the computation with three features: circle, triangle and background. Computing predictions for the 8 subsets and averaging the increases over the 6 orderings gives +0.61+0.61 for the circle, −0.19-0.19 for the triangle, and 0 for the background, which the prediction does not use. Adding these to the base value of 0.08 gives exactly the prediction of 0.50.

Computation: Kernel SHAP

Computing Eq. 8 directly requires model outputs for 2M2^M subsets. The paper proposed Kernel SHAP as an estimation method that works for any model. It is the same "weighted linear regression" as LIME, with only the choice of weights changed.

  1. Prepare background data (a few inputs selected from the training data). Replace absent features with values from the background data, and take the average of the outputs as fx(z′)f_x(z') (the approximation in Eq. 11).
  2. Choose subsets z′z' and compute fx(z′)f_x(z'). If MM is small, use all of them; if large, choose them by sampling.
  3. Assign each z′z' the following Shapley kernel weight πx′(z′)\pi_{x'}(z').
  4. Find the linear model gg that minimizes the weighted squared error L=∑z′[fx(z′)−g(z′)]2πx′(z′)L = \sum_{z'} \big[f_x(z') - g(z')\big]^2 \pi_{x'}(z'). No regularization is applied (Ω(g)=0\Omega(g) = 0). The coefficients ϕi\phi_i are the SHAP values.
πx′(z′)=M−1(M∣z′∣) ∣z′∣ (M−∣z′∣)\pi_{x'}(z') = \frac{M - 1}{\binom{M}{|z'|}\, |z'|\, (M - |z'|)}

Theorem 2 shows that a LIME-style regression satisfies the three properties (that is, yields Shapley values) only when this weight and squared error are used without regularization. When ∣z′∣|z'| is 0 or MM, the weight is infinite, so ϕ0=fx(∅)\phi_0 = f_x(\varnothing) and f(x)=∑i=0Mϕif(x) = \sum_{i=0}^{M} \phi_i always hold. In practice, these two conditions are used to eliminate two variables before solving the regression.

As the formula shows, the Shapley kernel gives large weights to z′z' that contain almost no features and to z′z' that contain almost all of them, and it is symmetric in the number of included features (Figure 2A of the paper). Its shape is completely different from LIME's kernel, which weights examples more heavily the closer they are to the original input.

When the model type is known, faster methods are available.

MethodApplicable modelsIdea
Linear SHAPLinear models f(x)=∑jwjxj+bf(x) = \sum_j w_j x_j + bIf features are independent, ϕi=wi(xi−E[xi])\phi_i = w_i (x_i - E[x_i]) and ϕ0=b\phi_0 = b
Low-Order SHAPModels with a small number of features MMSolve the Kernel SHAP regression over all subsets (complexity O(2M+M3)O(2^M + M^3))
Max SHAPMax functionsSort the inputs and compute the probability that each input raises the maximum (O(M2)O(M^2))
Deep SHAPNeural networksBuild DeepLIFT multipliers from the SHAP values of small components (linear layers, max pooling, activation functions) and backpropagate them with the chain rule

Experiments in the paper

The paper evaluates SHAP on three aspects: computational efficiency, agreement with human intuition, and explaining class differences. The results are shown in figures.

Computational efficiency. The contribution of one feature was estimated for a decision tree that uses all 10 features and for one that uses only 3 of 100 features. Kernel SHAP converged to the correct Shapley values with fewer model evaluations than Shapley sampling values. LIME's values deviated substantially from the Shapley values.

Agreement with human intuition. People were asked to allocate the output of simple models among the features, and their answers were compared with each method.

ExampleModelAnswer of humans and SHAPOther methods
Sickness score (30 people)2 if both fever and cough, 5 if only one, 0 if neither. Fever and cough are present, so the output is 21 each to fever and coughLIME gives negative values to fever and cough
Prize for three people (52 people)The prize is the maximum number of correct answers among the three. They got 5, 4 and 0 correct, so the prize is 5 dollars3 dollars, 2 dollars, 0 dollarsThe original DeepLIFT gives all 5 dollars to the first person

The paper notes that SHAP's result on the max example answers the open question in DeepLIFT of how to handle max pooling.

Explaining class differences. To turn the MNIST digit 8 into a 3, 20% of the pixels chosen by each method's contributions were removed, and the change in log-odds was compared over 20 images. SHAP (Kernel SHAP, 50,000 samples) produced larger changes than the original DeepLIFT, a new DeepLIFT made closer to Shapley values, and LIME.

Caveats in practice

In practice, SHAP values are usually computed assuming features are independent, replacing absent features with values from the background data (Eq. 11). If features are strongly correlated, the model is evaluated on combinations of inputs that cannot occur in reality, and the contributions are affected. The choice of background data also changes both the base value ϕ0\phi_0 and the contributions.

Keep the following points in mind as well.

  • Heavy computation: Exact computation requires 2M2^M subsets. Even Kernel SHAP repeats thousands to tens of thousands of model evaluations (50,000 samples in the paper's MNIST example).
  • Too many features at the pixel level: For images, group pixels into superpixels or similar units to reduce the number of features.
  • Each approximation makes different assumptions: Deep SHAP uses DeepLIFT's chain rule, so it involves an approximation that linearizes the model component by component. Kernel SHAP has variance from sampling.
  • Contributions are not causal: SHAP values describe "which features this model relied on for this input," not real-world cause and effect.

Comparison with other explanation methods

The table below compares SHAP with explanation methods it is often compared against, from the same perspectives.

MethodWhat it usesNeeds model internalsContributions sum to the predictionConsistencyComputation
LIMELinear regression weighted by proximityNoNoNot satisfiedThousands of predictions
SHAP (Kernel SHAP)Linear regression weighted by the Shapley kernelNoYesSatisfiedThousands to tens of thousands of predictions
SHAP (Deep SHAP)Backpropagation of multipliers built from per-component SHAP valuesYesYes (approximate)ApproximateBackpropagation of the same form as DeepLIFT
DeepLIFTBackpropagation of differences from a reference with layer-wise rulesYesYesNot satisfied1 backward pass
Integrated GradientsIntegral of gradients from a baseline to the inputYes (gradients)Yes—20 to 300 backward passes

The consistency column follows the discussion in the SHAP paper. Integrated Gradients is not covered in the SHAP paper.

Rough guidelines for choosing:

  • For tabular data or models without gradients, when theoretically grounded contributions are needed: Use Kernel SHAP.
  • For fast computation on neural networks: Use Deep SHAP or DeepLIFT.
  • For per-pixel contributions on images computed from gradients: Use Integrated Gradients.
  • For lightweight computation when a rough explanation is enough: Use LIME.

PyTorch example

Show code
python
import itertools
import math
import torch

'''
A small implementation of Kernel SHAP (Theorem 2 of Lundberg and Lee 2017). Uses all subsets when the number of features M is small.
Absent features are replaced with background data values and averaged (Eq. 11: assumes feature independence)
'''


@torch.no_grad()
def kernel_shap(model, x, background, target):
  # x: [M], background: [B, M] (inputs selected from training data). model maps [N, M] -> [N, num_classes]
  model.eval()
  M = x.numel()

  def f_x(mask):                                     # mask: [M] of 0/1. Features with 1 take x's values, 0 take background values
    z = background.clone()
    z[:, mask.bool()] = x[mask.bool()]
    return model(z)[:, target].mean()

  phi0 = f_x(torch.zeros(M))                         # Base value φ0 = E[f(z)]
  fx = f_x(torch.ones(M))                            # Prediction f(x)
  Z, y, w = [], [], []
  for k in range(1, M):                              # |z'| = 0, M have infinite weight, so treat them as constraints
    weight = (M - 1) / (math.comb(M, k) * k * (M - k))  # Shapley kernel
    for idx in itertools.combinations(range(M), k):
      mask = torch.zeros(M)
      mask[list(idx)] = 1
      Z.append(mask); y.append(f_x(mask) - phi0); w.append(weight)
  Z, y, w = torch.stack(Z), torch.stack(y), torch.tensor(w)
  # Eliminate the last feature's φ with the constraint Σφ = f(x) − φ0, then solve by weighted least squares
  A = Z[:, :-1] - Z[:, -1:]
  b = y - Z[:, -1] * (fx - phi0)
  sw = w.sqrt()[:, None]
  phi = torch.linalg.lstsq(A * sw, b[:, None] * sw).solution[:, 0]
  phi = torch.cat([phi, (fx - phi0 - phi.sum())[None]])
  return phi0, phi                                   # φ0 + Σ φ = f(x) (Property 1)


# Example: a small model with 4 features
model = torch.nn.Sequential(torch.nn.Linear(4, 16), torch.nn.ReLU(), torch.nn.Linear(16, 2))
background = torch.randn(50, 4)
x = torch.randn(4)
phi0, phi = kernel_shap(model, x, background, target=1)
print(phi0.item(), phi.tolist(), (phi0 + phi.sum()).item())

FAQ

Q. How do SHAP values differ from LIME's coefficients?
A.

Both are coefficients of a linear model whose inputs indicate whether each feature is present or absent. The difference lies in the weights and regularization used for fitting. LIME chooses its proximity kernel and limit on the number of features heuristically, so its coefficients do not sum to the prediction and do not satisfy consistency. SHAP uses the Shapley kernel without regularization, so its coefficients are Shapley values and sum to f(x)−ϕ0f(x) - \phi_0.

Q. What should be used as background data?
A.

Choose a set of inputs that represents "knowing nothing." In many cases, a few inputs selected from the training data are used. The base value ϕ0\phi_0 is then the average prediction over them, and the SHAP values split, feature by feature, "how far this input's prediction is from that average." Since changing the background changes the contributions, state which background was used along with the explanation.

Q. What does a negative SHAP value mean?
A.

It means that the presence of that feature pushed the prediction below the base value. For example, in the diagram at the top, the triangle has a SHAP value of −0.19-0.19, meaning its presence lowers the probability of class c. Adding all positive and negative values gives the difference between the prediction and the base value.

References

  1. S. M. Lundberg and S.-I. Lee, "A Unified Approach to Interpreting Model Predictions," Advances in Neural Information Processing Systems 30 (NIPS), 2017(arXiv:1705.07874).
  2. M. T. Ribeiro, S. Singh, and C. Guestrin, "\"Why Should I Trust You?\": Explaining the Predictions of Any Classifier," Proceedings of the 22nd ACM SIGKDD International Conference on Knowledge Discovery and Data Mining (KDD), pp. 1135–1144, 2016(arXiv:1602.04938).
  3. A. Shrikumar, P. Greenside, and A. Kundaje, "Learning Important Features Through Propagating Activation Differences," Proceedings of the 34th International Conference on Machine Learning (ICML), PMLR 70, pp. 3145–3153, 2017(arXiv:1704.02685).