Sub topic 10
Summarizing a whole model
A single SHAP explanation covers one prediction. The same SHAP values, stacked across many rows, also describe the model as a whole. This chapter shows how to build that summary and read it. It also covers what the summary cannot tell you.
I assume you can fit a scikit-learn model, use pandas and NumPy, and have read the earlier chapters on the baseline, additivity and the Explanation object.
From rows to a model summary
A SHAP explanation for a dataset is a matrix. Each row is a prediction and each column is a feature. Entry [i, j] is how much feature j moved prediction i away from the baseline. Local plots read one row. Global plots aggregate the columns.
The setup below is the one from the earlier chapters. Run it first, because every example here reuses sv.
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import shap
from sklearn.datasets import load_diabetes
from sklearn.ensemble import GradientBoostingRegressor
X, y = load_diabetes(return_X_y=True, as_frame=True)
model = GradientBoostingRegressor(random_state=0).fit(X, y)
explainer = shap.TreeExplainer(model)
sv = explainer(X)
print(sv.values.shape)The model predicts a numeric disease-progression score. SHAP values are therefore in the same units as that score.
The bar plot: average impact
The simplest global summary is the mean absolute SHAP value of each feature.
shap.plots.bar(sv)Passing a two-dimensional Explanation makes bar compute sv.abs.mean(0) for you. The bars are sorted from largest to smallest. Each bar answers one question: on average, how many output units does this feature move a prediction, in either direction?
You can compute the same numbers yourself. This is useful when you want them in a table or a report.
importance = pd.Series(
np.abs(sv.values).mean(axis=0), index=X.columns
).sort_values(ascending=False)
print(importance.round(2))The absolute value matters. Without it, a feature that adds 20 to half the rows and subtracts 20 from the other half would average to zero and look irrelevant.
Why mean absolute value is not the only summary
Mean absolute SHAP value suits a feature that matters a little for everyone. It can hide a feature that matters a lot for a few rows. You can switch the aggregation with the Explanation methods:
shap.plots.bar(sv.abs.max(0)) # largest single effect per feature
shap.plots.bar(sv.abs.mean(0)) # same as shap.plots.bar(sv)If the two orderings disagree, the model has features with rare but large effects. That is worth knowing. A fraud model, for example, may rely on a feature that fires on 1% of rows.
Comparing groups with cohorts
The cohorts method splits the rows into groups and draws one bar per group per feature. Pass a list of labels, one per row.
sex_label = np.where(X["sex"] > 0, "sex above 0", "sex at or below 0")
shap.plots.bar(sv.cohorts(sex_label).abs.mean(0))Use this to check whether the model relies on different features for different segments. Keep the cohorts large enough that a mean over each is stable.
The beeswarm plot: direction and spread
A bar shows size but not direction. The beeswarm plot shows every SHAP value, so you can see both.
shap.plots.beeswarm(sv)Read it like this:
- Each row of dots is one feature. Features are ordered by mean absolute SHAP value, so the top of the plot matches the top of the bar plot.
- Each dot is one row of your data. Its horizontal position is that row's SHAP value for the feature.
- The vertical scatter inside a row of dots only shows density. Where dots pile up, many rows share similar SHAP values.
- Color is the feature's own value for that row, from low (blue) to high (red).
- Zero on the horizontal axis means "no change from the baseline."
Suppose the bmi row has red dots on the right and blue dots on the left. That means high BMI values push the predicted score up and low BMI values push it down. The model has learned a roughly increasing relationship. If red and blue dots are mixed together on both sides, the feature's effect depends on something else. A scatter plot or interaction values (later chapters) is the next step.
A long tail of dots far from zero, with most dots close to it, is the pattern that the mean-absolute bar understates. The beeswarm makes it visible.
Controlling what is shown
With many features the plot gets crowded. These arguments help:
shap.plots.beeswarm(sv, max_display=6)
shap.plots.beeswarm(sv, order=sv.abs.max(0))max_display keeps the top features and sums the rest into one row labeled "Sum of N other features." order accepts any per-feature Explanation summary, so you can sort by maximum effect rather than mean effect. For large datasets, beeswarm subsamples the rows it draws. You can also pass sv[:1000] yourself.
A missing value in a feature is drawn in gray, since it has no position on the blue-to-red scale.
Putting the plots side by side
The two plots answer different questions, so they work best together.
| Question | Plot | What you read |
|---|---|---|
| Which features matter most on average? | Bar | Length of each bar |
| Does a feature matter a lot for a few rows? | Beeswarm, or bar with `abs.max(0)` | Dots far from zero |
| Which way does a feature push predictions? | Beeswarm | Color against horizontal position |
| Is the effect the same for everyone? | Beeswarm, then scatter | Spread within one row of dots |
| Does the model treat groups differently? | Bar with cohorts | Bar lengths per cohort |
Reading global plots correctly
Global plots look authoritative, and that makes them easy to over-read. Keep these points in mind.
Units come from the model output
The horizontal axis is in the units of the explained output. For this regression model that is the disease score. For a classifier explained on its raw margin, the units are log-odds, not probabilities. Mean absolute values from models with different output scales cannot be compared. A feature with a bar of 20 in one model and 0.4 in another says nothing about which model uses it more.
Importance is relative to the background data
The values are measured against a baseline built from background data. A different background changes the values, so the plots change too. State which dataset you explained when you share a plot.
Correlated features share credit
If two features carry nearly the same information, the model may use either, and SHAP splits credit between them. Each can look weaker than the pair actually is. Check the correlation matrix before concluding that a feature is unimportant. In the diabetes data, several blood-serum measurements (s1 to s5) are strongly related to each other, so read their bars as a group.
Importance is not causation
A large bar says the model leans on a feature. It does not say that changing the feature in the real world would change the outcome. The beeswarm shows association learned from data, including any proxies and leaks.
Global plots reflect the data you pass in
Explaining the training set shows how the model behaves on data it has seen. Explaining a held-out set, or recent production data, shows how it behaves on the data you care about. Both are legitimate, but they answer different questions. Comparing them can reveal drift.
Cost grows with rows
Tree explainers are fast, but model-agnostic explainers need many model calls per row. For those, explain a random sample of a few hundred to a few thousand rows. Global summaries stabilize quickly with sampling, and the plots do not need every row.
sample = X.sample(200, random_state=0)
sv_sample = explainer(sample)
shap.plots.beeswarm(sv_sample)Common mistakes
- Reading the horizontal position of a beeswarm dot as the feature value. It is the SHAP value. The feature value is the color.
- Comparing mean absolute values across models with different output units or scales.
- Dropping a low-ranked feature without checking whether a correlated feature absorbed its credit.
- Explaining only the training set and describing the result as how the model behaves in production.
- Passing a single-row
Explanationtobarand expecting a global result. One row gives a local bar chart.
Exercise
A beeswarm plot for a loan-default model shows income near the top. Its dots are mostly clustered near zero, but a handful lie far to the right and are colored blue. A teammate says "income is unimportant because most dots are near zero." Give two things you would check or say in response.
Show answer
First, the mean absolute SHAP bar can understate a feature with rare large effects, so compare it with the abs.max(0) ordering. The dots far to the right show that for some rows income strongly raises the predicted risk. Second, the blue color means those rows have low income values, so low income pushes the prediction up for those rows. Also check whether income is correlated with another feature, such as employment length, that may be sharing its credit. Finally, this describes what the model uses, not a causal effect of income on default.
Exercise
You fit two regressors on the same data. Model A predicts house price in dollars, and Model B predicts the same price in thousands of dollars. Feature area has a mean absolute SHAP value of 25,000 in A and 25 in B. Does B rely on area less?
Show answer
No. The two values describe the same effect in different units, because B's output is A's divided by 1,000. Mean absolute SHAP values carry the units of the explained output, so they can only be compared within one model or across models with the same output scale. Compare each feature's share of the total, for example its bar divided by the sum of all bars.