A model predicts that a house is worth $156,000, while the average house in the data is worth $207,000. A buyer, a bank or a regulator asks: why is this one $51,000 below average? "The model said so" isn't an answer. SHAP (SHapley Additive exPlanations) gives one: it splits the $51,000 gap between the features, so you can say "the location took off $18,000, crowded households took off $41,000" and so on, with the pieces adding up exactly to the prediction.
The idea comes from game theory. When a team wins a prize, how do you split it fairly between players who helped in different amounts and combinations? Lloyd Shapley's answer: average each player's extra contribution over every order in which the team could have been assembled. SHAP treats the features as the players and the prediction as the prize. Explaining model predictions with SHAP works for any model, and for tree models it's fast enough to explain thousands of predictions in a second.
What you need first: gradient boosting explained, permutation importance from the Adult income random forest project, and error analysis.
Install it with pip install shap.
Key terms
- Shapley value: a player's average extra contribution over every order in which the players could join.
- SHAP value: a feature's Shapley value for one prediction: how much it moved the prediction away from the average.
- Base value: the model's average prediction, where every explanation starts.
- Additivity: base value + all SHAP values for a row = the model's prediction for that row.
- Local vs global explanation: why one prediction came out as it did, against which features matter across all predictions.
Shapley values by hand
A tiny made-up model predicts house prices (in $1,000s) from two facts: whether the house is big, and whether it's near a station. For a big house near a station, here is what the model would predict knowing different subsets of the facts:
| Known facts | Prediction |
|---|---|
| None (the average) | 100 |
| Big only | 140 |
| Near station only | 120 |
| Both | 180 |
The total to explain is 180 − 100 = 80. The two features can be "added" in two orders:
- Size first (+40, from 100 to 140), then station (+40, from 140 to 180).
- Station first (+20, from 100 to 120), then size (+60, from 120 to 180).
Size added 40 in one order and 60 in the other; its Shapley value is the average, 50. The station added 40 and 20: average 30. And 50 + 30 = 80, the whole gap.
from itertools import permutations
prediction = {(): 100, ("big",): 140, ("station",): 120, ("big", "station"): 180}
def value(known):
return prediction[tuple(sorted(known))]
shapley = {"big": 0, "station": 0}
orders = list(permutations(["big", "station"]))
for order in orders:
known = []
for feature in order:
before = value(known)
known.append(feature)
shapley[feature] += (value(known) - before) / len(orders)
print(shapley, "total:", sum(shapley.values()))
{'big': 50.0, 'station': 30.0} total: 80.0
permutations lists every order of the features. tuple(sorted(known)) turns the known features into the same key whatever order they were added in.
Notice the interaction: being big is worth more when the house is also near a station (60 rather than 40). Shapley values don't ignore that; they share it fairly between the two features. With many features there are far too many orders to list, but for tree models SHAP has an exact shortcut.
Explain one prediction
Gradient boosting on California house prices, as in the earlier lessons in this module:
Download the data: california-housing.csv (1.9 MB), or from the original source, the StatLib repository. The code below loads it for you, so you only need the file to open it in a spreadsheet or work offline: load it with
pd.read_csv("california-housing.csv").
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import shap
from sklearn.datasets import fetch_california_housing
from sklearn.model_selection import train_test_split
from sklearn.ensemble import HistGradientBoostingRegressor
housing = fetch_california_housing(as_frame=True)
X_train, X_test, y_train, y_test = train_test_split(housing.data, housing.target, test_size=0.2, random_state=0)
model = HistGradientBoostingRegressor(random_state=0).fit(X_train, y_train)
explainer = shap.TreeExplainer(model)
explanation = explainer(X_test.iloc[:1000])
first = explanation[0]
print(f"base value (average prediction): {first.base_values:.3f}")
print(f"sum of SHAP values: {first.values.sum():+.3f}")
print(f"base + SHAP values: {first.base_values + first.values.sum():.3f}")
print(f"model's prediction: {model.predict(X_test.iloc[[0]])[0]:.3f}")
base value (average prediction): 2.071
sum of SHAP values: -0.509
base + SHAP values: 1.562
model's prediction: 1.562
TreeExplainer uses the exact shortcut for tree models. explainer(...) returns an explanation object for the first 1,000 test districts, and explanation[0] is the first district's. X_test.iloc[[0]], with double brackets, keeps the row as a one-row table, the shape predict expects.
The average prediction is 2.071 ($207,100). The SHAP values for this district add up to −0.509, and 2.071 − 0.509 = 1.562, exactly the model's prediction of $156,200. That additivity is what makes SHAP explanations easy to read: every dollar of the gap is assigned to some feature.
A waterfall plot shows how each feature moves the prediction from the base value to the final answer:
shap.plots.waterfall(first, show=False)
plt.show()
show=False lets matplotlib's plt.show() display the chart, the same as every other chart in this course.
Read it from the bottom up. Starting at the average of 2.071, longitude takes off 0.67 and latitude adds back 0.49. These two always work as a pair: together they say where the district is, at 32.58° N, 117.05° W, near San Diego, and the location as a whole takes off 0.18, about $18,000. SHAP splits the location between two columns, so each column's number is large while their sum is modest; read related features together. Average occupancy, 4.18 people per household against a typical 2.8, takes off 0.41: crowded households go with cheaper housing. Median income adds only 0.06 here, because 4.15 is close to the typical income, so it barely moves this district away from the average.
From one prediction to the whole model
Each district has its own explanation. Put 1,000 of them together and the overall pattern appears. Predict first: median income is the strongest single feature in this data. Will it also have the largest average SHAP value?
importance = pd.Series(np.abs(explanation.values).mean(axis=0), index=X_test.columns)
print(importance.sort_values(ascending=False).round(3))
MedInc 0.453
Latitude 0.403
Longitude 0.345
AveOccup 0.218
AveRooms 0.083
HouseAge 0.053
AveBedrms 0.026
Population 0.018
dtype: float64
np.abs(...).mean(axis=0) averages the size of each feature's SHAP values over the 1,000 districts, ignoring whether they pushed up or down.
Yes, but only just: median income has the largest average effect (0.453), with latitude (0.403) and longitude (0.345) close behind. The bottom of the list matters too: average bedrooms and population move predictions by 0.026 and 0.018 on average, so the model barely uses them. On the one district above, income mattered little and location a lot; across all districts, income leads. Local and global explanations answer different questions.
A beeswarm plot shows every district's SHAP value for every feature, coloured by the feature's value:
shap.plots.beeswarm(explanation, show=False)
plt.show()
Each dot is one district. Its position says how much that feature pushed the prediction, and its colour says whether the feature's value was high (red) or low (blue). For median income, red dots stretch far to the right, as far as +2.4: high incomes push predictions up a lot, low ones (blue) pull them down. For latitude and longitude, the colours reverse: higher values, meaning further north and further east (away from the coast), push prices down. For average occupancy, crowding pushes down. The long right tail for income, against a short left one, shows an effect that is larger for the richest districts than for the poorest.
How one feature's effect changes
A scatter plot of one feature's SHAP values against its values shows the shape of its effect, which a single importance number hides:
shap.plots.scatter(explanation[:, "MedInc"], show=False)
plt.show()
explanation[:, "MedInc"] keeps every district's explanation for the MedInc column only.
The effect of income rises steadily, almost in a straight line, from about −0.8 at an income of 1 to about +1.8 at 8, then flattens: incomes above 9 all add about +2. That flattening is likely partly the $500,001 cap from error analysis: the richest districts can't be predicted much higher because their recorded values stop at the cap. The grey histogram shows where the data is: few districts have incomes above 8, so that part of the curve rests on few points.
See it fail: two copies of the same feature
SHAP shares credit fairly between features, and "fairly" has a catch. Experiment: add a near-copy of median income (the same value plus tiny random noise), retrain, and look at the importances again.
rng = np.random.default_rng(0)
X_train_copy, X_test_copy = X_train.copy(), X_test.iloc[:1000].copy()
X_train_copy["MedInc_copy"] = X_train_copy["MedInc"] + rng.normal(0, 0.01, len(X_train_copy))
X_test_copy["MedInc_copy"] = X_test_copy["MedInc"] + rng.normal(0, 0.01, len(X_test_copy))
model_copy = HistGradientBoostingRegressor(random_state=0).fit(X_train_copy, y_train)
explanation_copy = shap.TreeExplainer(model_copy)(X_test_copy)
importance_copy = pd.Series(np.abs(explanation_copy.values).mean(axis=0), index=X_test_copy.columns)
print(importance_copy.sort_values(ascending=False).round(3).head(5))
Latitude 0.404
Longitude 0.348
MedInc 0.245
AveOccup 0.223
MedInc_copy 0.208
dtype: float64
rng.normal(0, 0.01, n) adds noise far smaller than income's own spread, so the copy carries the same information.
Median income seems to have lost almost half its importance: 0.245 instead of 0.453, now behind latitude and longitude. The other half went to MedInc_copy (0.208). Together they add up to roughly the old total, but anyone reading this chart alone would conclude income matters less than location. SHAP split the credit fairly between two features that carry the same information, as Shapley values must. Before reading importances, check for strongly correlated features, and consider grouping them.
SHAP, permutation importance or coefficients?
| Question | Tool | Notes |
|---|---|---|
| Why did the model predict this for this row? | SHAP waterfall | Local; adds up exactly to the prediction |
| Which features matter most overall? | Mean absolute SHAP, or permutation importance | Both share credit between correlated features |
| How does a feature's effect change with its value? | SHAP scatter, or partial dependence | Shows curves and thresholds |
| A linear model's effects | Coefficients on scaled features | Already additive; SHAP gives the same story |
| Does a feature cause the outcome? | None of these | Explanations describe the model, not the world |
Practice
- Without running code: with three features, how many orders are there to average over? With 8?
Show the answer
3! = 6 orders for three features, and 8! = 40,320 for eight. That's why exact Shapley values are impractical for most models, and why TreeExplainer's shortcut for trees matters.
- In the hand-worked example, change "Both" to 160. What are the new Shapley values?
Show the answer
prediction[("big", "station")] = 160
shapley = {"big": 0, "station": 0}
for order in orders:
known = []
for feature in order:
before = value(known)
known.append(feature)
shapley[feature] += (value(known) - before) / len(orders)
print(shapley)
{'big': 40.0, 'station': 20.0}
Size: (40 + 40) ÷ 2 = 40. Station: (20 + 20) ÷ 2 = 20. With 160, the two features no longer interact: each adds the same amount whatever the order, so each Shapley value equals its simple effect, and 40 + 20 = 60 = 160 − 100.
- Find the test district (among the first 1,000) where
MedIncpushed the prediction up the most. What is its median income?
Show the answer
i = int(explanation[:, "MedInc"].values.argmax())
print(i, X_test.iloc[i]["MedInc"], round(float(explanation[i, "MedInc"].values), 3))
266 9.2858 2.375
District 266 in that list, with a median income of 9.29, one of the highest in the data, where income pushes the prediction up by 2.375, nearly $240,000. That's the top of the scatter plot.
- A SHAP explanation says
Latitudelowered a district's price by $40,000. Does that mean moving the house north would lower its value?
Show the answer
No. SHAP describes what the model does with the features it was given, not cause and effect in the real world. Latitude stands in for many things the model can't see, such as climate, jobs and neighbourhood. Moving a house doesn't change those, so the explanation can't be read as a recipe.
- Why might a bank prefer a SHAP waterfall over a feature importance chart when explaining a rejected loan?
Show the answer
Importance is global: it says which features matter on average across all customers. The applicant wants to know what drove their decision, and a waterfall gives exactly that, in amounts that add up to their score.
Interview questions
What are SHAP values?
Shapley values from cooperative game theory applied to a single prediction: each feature's average marginal contribution to the prediction over all orders of adding features. They're additive: the base value (average prediction) plus the SHAP values equals the prediction.
What's the difference between SHAP and permutation importance?
SHAP gives local explanations, one value per feature per prediction, which can be averaged into a global importance. Permutation importance is global only: it measures how much a validation score drops when a feature's values are shuffled.
What are the limitations of SHAP?
It explains the model, not causality; correlated features share credit in ways that can hide a feature's role; exact values are expensive except for trees and linear models; and approximations for other models depend on a background dataset and can be slow.
Key takeaways
- A SHAP value says how much one feature moved one prediction away from the average prediction.
- The base value plus all SHAP values equals the prediction exactly.
- Averages of absolute SHAP values give global importance; beeswarm and scatter plots show direction and shape.
- Correlated features split credit, so a feature can look less important than it is.
- SHAP explains the model's behaviour, not how the world works.
Frequently asked questions
Does SHAP work for neural networks?
Yes, with shap.DeepExplainer, GradientExplainer or the model-agnostic KernelExplainer. These are approximate and slower than TreeExplainer, so explain a sample of rows rather than all of them.
Why do my SHAP values not add up to the predicted probability?
For classifiers, tree explainers often work in log-odds, the model's raw score before the sigmoid. The values add up to the raw score; apply the sigmoid to the total to get the probability.
How many rows should I explain?
For global plots, a few hundred to a few thousand representative rows are plenty. For local explanations, explain just the rows someone asks about.
What to learn next
- Check whether a model treats groups of people fairly in fairness and bias in machine learning, the next lesson.
- Revisit permutation importance in feature selection methods.
- Revisit how the model behind these explanations is built in gradient boosting explained.