SHAP values

Explain single predictions by sharing the outcome among the features in a fair way.

Lesson 57 of 6614 minAdvanced

You will learn to

  • Explain Shapley values intuitively
  • Read a SHAP summary and a single-row explanation
  • Know the cost and limits of SHAP

Before this lesson

Intuition

Three colleagues build a product together and earn 100 in profit. How much of the profit is each one's? Splitting by hours or by title is arbitrary. A fairer idea is to ask: how much does the profit grow when this person joins a team, averaged over every order in which the team could have been put together? That average is a person's Shapley value, and it comes from game theory.

SHAP applies the same idea to a prediction. The "team" is the set of features, and the "profit" is the prediction minus a reference. Start from the base value, the average prediction over your data. Then ask how much each feature of this particular row pushes the prediction up or down. The pushes add up exactly to the prediction.

That gives something permutation importance cannot: an explanation of one prediction. "This house was predicted at 275 because its size added 40, its age added 15, and its distance from the centre took away 30." Averaging the sizes of these pushes across many rows then gives a global view.

Picture it

A waterfall explains one row. It starts at the average prediction, each bar adds or subtracts the contribution of one feature, and the last bar is the prediction for this row.

Average prediction250Size: 120 m2+40Age: 5 years+15Distance: 12 km-30This prediction275
SHAP explanation of one prediction (illustrative numbers): 250 + 40 + 15 - 30 = 275.

A summary plot stacks many rows: one dot per row and feature, positioned by its SHAP value and coloured by the feature value. It shows both the importance (how wide the dots spread) and the direction (high values push up or down).

The math

For a model ff, a row xx and a set of features FF with ∣F∣=M\lvert F \rvert = M, let v(S)v(S) be the model's expected output when only the features in the subset SS are known. The Shapley value of feature ii is

ϕi=∑S⊆F∖{i}∣S∣! (M−∣S∣−1)!M! [v(S∪{i})−v(S)]\phi_i = \sum_{S \subseteq F \setminus \{i\}} \frac{\lvert S\rvert!\,(M-\lvert S\rvert-1)!}{M!}\,\big[v(S \cup \{i\}) - v(S)\big]

The fraction is the share of orderings in which exactly the features of SS come before ii. The bracket is the gain from adding ii.

Two properties make the result trustworthy:

  • Additivity (local accuracy). With ϕ0=v(∅)\phi_0 = v(\varnothing) as the base value, f(x)=ϕ0+∑i=1Mϕif(x) = \phi_0 + \sum_{i=1}^{M}\phi_i.
  • Fairness. Features that contribute the same get the same value, and a feature that never changes the output gets zero.

The sum runs over 2M−12^{M-1} subsets, which is too many for dozens of features. Tools therefore use shortcuts: an exact fast algorithm for tree models (TreeSHAP) and sampling-based approximations for everything else.

Worked example

Two features, size and distance. Suppose the expected output with different features known is (illustrative):

  • nothing known: 250 (the base value)
  • only size known: 280
  • only distance known: 230
  • both known: 260 (the prediction for this house)

With M=2M = 2 there are two orderings, each with weight 1/2.

  1. Size. Joining first: 280 - 250 = +30. Joining after distance: 260 - 230 = +30. The average is ϕsize=30\phi_{\text{size}} = 30.
  2. Distance. Joining first: 230 - 250 = -20. Joining after size: 260 - 280 = -20. The average is ϕdistance=−20\phi_{\text{distance}} = -20.
  3. Check. 250 + 30 - 20 = 260, which is the prediction. The values add up.

Here the contributions did not depend on the order. When features interact, the two orderings give different gains, and averaging them is exactly what makes the split fair.

How mlflow does it

mlflow does not draw SHAP plots in the app today. The Explainability group of the Plots tab has Feature importance and Permutation importance. To get SHAP values, download the model and compute them yourself.

  1. On the model candidate page, use the download or export options. The bundle contains a file called pipeline.joblib, which is the fitted pipeline with its preprocessing.
  2. In a notebook with the shap package installed, load it and explain a sample of rows:
python
import joblib
import shap

pipe = joblib.load("pipeline.joblib")
model = pipe[-1]                        # the estimator
X_ready = pipe[:-1].transform(X_test)   # the data as the estimator sees it

explainer = shap.Explainer(model, X_ready)
values = explainer(X_ready[:200])

shap.plots.beeswarm(values)    # summary over many rows
shap.plots.waterfall(values[0])  # one row

The snippet assumes the last step of the pipeline is the estimator and that X_test is a data frame with the original columns. Explain a sample of a few hundred rows first, because some models are slow. See the docs page on downloading the model for the formats.

Common mistakes

  • Reading SHAP as causation. The values describe how the model uses its inputs. A large value for a proxy feature does not mean that changing it would change the outcome.
  • Explaining the whole dataset with a slow explainer. The cost can be large for non-tree models. Sample rows and use the tree-specific explainer where it applies.
  • Ignoring correlated features. Credit is shared between near copies, and some methods evaluate unrealistic combinations of feature values. Group related features before telling a story.
  • Explaining on the wrong scale. For a classifier the values may be in log-odds, not probability. State the scale when you show a number to a stakeholder.
  • Explaining the training rows only. A model can behave differently on new data. Explain held-out rows too, and compare.

Try it in mlflow

Download a model to explain

  1. Open Runs, choose a run and open a model candidate.
  2. Use Download, or the export options, to get the model bundle.
  3. In a notebook, load the fitted pipeline from the bundle and run the SHAP snippet from this lesson on a few rows.
Open in mlflow

Read in the docs

Check your understanding

  1. 1. A model predicts 275 for one house. The average prediction is 250. The SHAP values are +40 (size), +15 (age) and -30 (distance). What is true?
  2. 2. What does the mean absolute SHAP value of a feature, across many rows, give you?
  3. 3. Which is a real limit of SHAP?