Back to Tutorials
Machine Learning
Advanced

SHAP: Why Did the Model Say That?

Split a prediction into fair shares by revealing its inputs in every order, then use SHAP to catch a model that is quietly cheating.

11 minInteractive: drag, click and try things as you read


A delivery app says your dinner will take 50 minutes. Why so long? SHAP answers questions like that for almost any model: it splits a prediction into one share per input (the distance, the rain, the queue in the kitchen), and the shares add up exactly to the difference from an ordinary prediction. Each input’s share is its average contribution over every order in which the inputs could be revealed. Here you’ll work one out by hand, then use SHAP to catch a model that has quietly found a way to cheat.

Why ask a model why?#

A prediction on its own is hard to trust and harder to fix. If you know which inputs pushed it up or down you can check it against common sense, find the bug when it’s wrong, and explain it to the person affected. Sometimes that last part is required. In US lending, for example, a lender who turns down an application must be able to give the applicant the specific reasons.

For a straight-line model, the answer is easy: each input’s contribution is its weight times how far it is from average. Most useful models aren’t straight lines. In a boosted tree model or a neural network, inputs combine: rain might cost a minute on a short trip and ten on a long one. Then “how much of this is because of the rain?” stops having an obvious answer.

Splitting the credit#

Take a small made-up model of delivery time. It starts at 8 minutes, adds 2.5 per kilometre and 1.5 per order waiting ahead of yours in the kitchen, and two effects that interact. Rain slows the rider, so it costs more the longer the trip. At rush hour the kitchen is slower, so each order ahead costs more. Across 400 typical past deliveries, the model’s average prediction is 27.6 minutes.

Tonight’s delivery is 6 km, in the rain, at rush hour, with 5 orders ahead: 49.8 minutes. To share out the extra 22.2 minutes, a natural method is to reveal the four facts one at a time and see how much each one moves the prediction. Anything not yet revealed is filled in from those typical deliveries, and the predictions averaged.

Predict first

You reveal the rain first, then the distance. Next time, the distance first, then the rain. Does the rain get the same credit both times?

Try it
0102030405060minAverage delivery27.6

Before you know anything about this delivery, the best guess is the average: 27.6 minutes. Tap the facts in any order.

The delivery model is a made-up formula, so you can check the arithmetic; everything else is computed live. Unrevealed facts are filled in from 400 made-up past deliveries. Tap the four facts in any order, then average over all 24 orders.

Revealed first, the rain adds 5.1 minutes. Revealed after the distance, it adds 8.4. The distance has the same problem the other way round: 6.8 or 10.2. Both are right; they answer different questions. The extra cost of rain on a long trip belongs to the rain and the distance, and whichever is revealed second collects it.

The fair answer: average every order#

In 1953 the mathematician Lloyd Shapley asked a similar question about teams. When players combine to win a prize, and some combinations are worth more than the sum of their parts, how should the prize be shared? His answer, now called the Shapley value, is to imagine the players joining in every possible order and give each one their average contribution. (Shapley later shared the 2012 Nobel prize in economics, for related work on how to match people and resources fairly.)

In 2017 Scott Lundberg and Su-In Lee applied it to models: the players are the inputs, and the prize is the gap between this prediction and the average one. They called the result SHAP, for Shapley additive explanations. For four inputs there are 24 orders. Press “Average all 24 orders” in the figure.

Predict first

Each input’s credit is now an average over 24 orders. Do the four averages still add up to exactly 22.2 minutes, the gap between this delivery and the average one?

For tonight’s delivery: distance +8.5, rain +6.8, rush hour +5.1 and orders ahead +1.8, and 27.6 plus those is 49.8. Rain’s +6.8 sits exactly halfway between its two possible credits: the Shapley value splits the cost of rain on a long trip evenly between the rain and the distance. Try the other two deliveries as well. On the short wet one, the kitchen queue is the biggest reason for the wait, and the short distance takes 7.8 minutes off.

Shapley proved this is the only way to split credit that always adds up exactly, gives nothing to an input that never changes anything, gives equal shares to inputs that always contribute equally, and gives the sum of the two splits when two games are added together. That’s why SHAP became the standard.

From one prediction to the whole model#

One explanation tells you about one delivery. Explain a few hundred and plot them together, and you see how the whole model behaves: which inputs matter most, in which direction, and for whom. The average size of an input’s SHAP values is a common measure of its importance.

Now a model nobody wrote by hand. The next figure trains a gradient-boosted model in your browser on 2,000 made-up past deliveries. They follow the same formula plus luck (traffic, a slow lift). Then a colleague suggests a fifth input from the database: the star rating the customer gave. Test error drops from 4.6 minutes to 3.4. Ship it?

Predict first

With the rating added, which input will SHAP say matters most?

Try it

…

average miss on 500 test deliveries

…

average miss once live, with no rating yet

Training on 2,000 past deliveries…

Explaining 0 of 150 new deliveries…

Made-up deliveries; the model, its training and the SHAP values are all computed in your browser, using the same fill-in-from-typical-deliveries method as above, with 30 past deliveries as the typical ones. Each row is one input; each dot is one of 150 new deliveries. The number on the right is the input’s average share, in minutes.

Without the rating, distance matters most, moving a prediction by 5.5 minutes on average, then orders ahead at 4.2. Red dots on the right of the distance row say what you’d expect: long trips push predictions up. With the rating added, it jumps to the top at 5.9 minutes, more than twice any other input.

That should set off an alarm. The rating is left after the food arrives, so the app can’t know it when you place the order. It’s information from the future, a textbook case of data leakage: the test set has ratings too, so the test score looks better. Once live, the app would have to fill in a typical rating, and the average miss becomes 8.0 minutes, worse than the honest model’s 4.6. SHAP didn’t know the rating was a leak; it showed that the model relied on an input that had no business mattering that much.

What SHAP can’t tell you#

  • It explains the model, not the world. SHAP faithfully reports that the leaky model leans on ratings. That doesn’t mean ratings cause slow deliveries. Treat SHAP values as a description of what the model does, not of cause and effect.
  • “Compared with what?” is a choice. The values measure distance from an average prediction, and the typical cases you fill in from set that average. Against all deliveries, a 6 km trip is long; against deliveries from a restaurant out of town, it may be short.
  • Related inputs muddy the split. If two inputs carry the same information, credit can land on either. Filling in inputs independently can also create cases that never happen, like heavy rain on a cloudless day, and the model’s answers for those are guesses.
  • It’s one tool among several. Permutation importance (how much worse the model gets when an input is shuffled) and partial dependence plots (how the prediction changes as one input changes) answer related questions and make good cross-checks.

In code#

With the shap library (pip install shap scikit-learn) on scikit-learn’s diabetes dataset: 442 patients, 10 measurements each, and a score for how far the disease progressed a year later.

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)   # 442 patients, 10 measurements
model = GradientBoostingRegressor(random_state=0).fit(X, y)

explainer = shap.TreeExplainer(model, data=X.sample(100, random_state=0))
sv = explainer(X)                     # a SHAP value for every patient and measurement

first = sv[0]
print(f"{first.base_values:.3f} + {first.values.sum():.3f} = {model.predict(X.iloc[[0]])[0]:.3f}")
importance = np.abs(sv.values).mean(axis=0)
for name, v in sorted(zip(X.columns, importance), key=lambda t: -t[1])[:3]:
    print(f"{name}: {v:.1f}")
# 152.148 + 48.725 = 200.873
# s5: 23.9
# bmi: 22.3
# bp: 10.5

Passing data gives the explainer its typical cases, 100 patients here, exactly as the figures do. The first line checks the additivity: the average prediction plus the first patient’s SHAP values is the model’s prediction for that patient. The most important measurements are s5 (a blood serum measurement), body mass index and blood pressure. shap.plots.beeswarm(sv) draws the summary chart from the figure, and shap.plots.waterfall(sv[0]) the one-patient version.

What to remember

  • SHAP splits a prediction into one share per input, and the shares add up exactly to its difference from the average prediction.
  • Each share is the input’s average contribution over every order the inputs could be revealed in: the Shapley value from game theory.
  • Across many predictions it shows what the model relies on, which catches leaks and bugs, but it describes the model, not cause and effect.

Keep going

Sign in to save your place and keep a learning streak. Free, with Google.