Sub topic 11
How a feature's effect varies: scatter plots
This chapter assumes you can already compute an Explanation object with TreeExplainer and that you know the baseline-plus-sum-of-SHAP-values identity from earlier chapters. You should also be comfortable slicing pandas DataFrames and NumPy arrays. The bar and beeswarm plots show how important a feature is. They don't show how its effect changes as its value changes. The scatter plot (also called a dependence plot) shows that.
What a SHAP scatter plot shows
A SHAP scatter plot has one dot per row of data.
- The x-axis is the feature's value in that row.
- The y-axis is that feature's SHAP value in that row.
A point at (x = 0.05, y = +20) means that in that row, the feature value 0.05 pushed the prediction 20 units above the baseline. The units are the model's output units. For the diabetes regression below, they are units of the disease-progression target. For a classifier explained on the raw margin, they are log-odds.
Because every dot comes from a different row, the plot shows two things at once:
- The trend. How the average contribution changes as the feature value changes.
- The vertical spread. How much the contribution differs between rows that have nearly the same feature value.
The spread is what separates a SHAP scatter plot from a classic partial dependence curve. A partial dependence curve is a single line. A SHAP scatter plot shows the whole cloud around it.
Drawing a scatter plot
The setup below repeats the model from the earlier chapters so the code runs on its own.
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)
shap.plots.scatter(sv[:, "bmi"])Slicing sv[:, "bmi"] keeps all rows and selects one column by name. The result is still an Explanation. Its .values field holds the SHAP values for bmi, and its .data field holds the matching feature values. The plot function reads those two fields and draws them against each other.
Below the dots, the plot draws a light histogram of the feature values. Use it to judge how much data supports each part of the curve. A region with only a few rows can look dramatic and mean nothing.
Reading the trend
The shape of the cloud tells you how the model uses the feature. Common shapes:
| Shape of the cloud | What it says about the model |
|---|---|
| Rising line | Higher feature values push predictions up |
| Falling line | Higher feature values push predictions down |
| Flat band near zero | The model mostly ignores the feature |
| Step or sharp jump | The model uses a threshold, typical of trees |
| U or inverted U | Both low and high values push in the same direction |
| Wide vertical band at each x | The effect depends on other features |
Tree ensembles produce stepped, piecewise-constant shapes, because each tree splits on thresholds. If the plot looks jagged, that comes from the model and is not noise in the explainer. A smooth monotone trend through a jagged cloud is a fair summary.
You can check what the plot shows with a few lines of pandas. Bin the feature and summarize the SHAP values in each bin.
import pandas as pd
bmi = sv[:, "bmi"]
df = pd.DataFrame({"bmi": bmi.data, "shap": bmi.values})
df["bin"] = pd.qcut(df["bmi"], 5)
summary = df.groupby("bin", observed=True)["shap"].agg(["mean", "std", "count"])
print(summary)The mean column traces the trend, and the std column measures the vertical spread. For bmi, you should see the mean rise from the lowest bin to the highest bin. A large std inside a bin means the same bmi value contributes differently in different rows.
Reading the vertical spread
Take two rows with the same bmi but different SHAP values for bmi. Under a model where each feature acts independently, this can't happen. Two things can cause it:
- Interaction. The model uses
bmidifferently depending on another feature, such ass5. The samebmithen contributes more whens5is high. - Correlated features.
bmiis correlated with other features. The model may route part of the same signal through a correlated feature. Which feature gets the credit then depends on the row.
The first cause is the usual reason to look for spread. To find which feature is responsible, color the dots by a second feature.
shap.plots.scatter(sv[:, "bmi"], color=sv[:, "s5"])If the colors separate cleanly, with high s5 dots above low s5 dots at each x, then s5 modifies the effect of bmi. If the colors are mixed, s5 is not the reason for the spread.
You can also pass the whole Explanation as the color argument.
shap.plots.scatter(sv[:, "bmi"], color=sv)In this form, SHAP picks the coloring feature itself. It uses a heuristic that looks for the feature whose values best explain the leftover vertical variation after a trend is fitted. This is quick, but treat it as a suggestion. It is not the same as the SHAP interaction values covered in a later chapter, and it can pick a feature that is merely correlated with bmi.
How this differs from partial dependence
A partial dependence plot fixes one feature at each grid value for every row, then averages the model's predictions. It gives one curve for the model's average response.
A SHAP scatter plot uses the real rows. Each dot is the contribution of the feature's actual value in that row, measured against the background data. Two differences follow:
- The y-axis is centered. Partial dependence is on the scale of the prediction. SHAP values are contributions relative to the baseline, so a value of zero means "no change from the baseline average for this feature".
- The spread is visible. Partial dependence averages the interaction effects away. SHAP keeps them as vertical scatter.
For a model with no interactions, the mean SHAP value per x position and the partial dependence curve have the same shape, shifted vertically. With interactions, they can differ, and the difference is informative.
Practical details
- Select features by name.
sv[:, "bmi"]works whensvwas built from a DataFrame. For a plain NumPy array, use the column index, as insv[:, 2]. - Check units before comparing plots. Two scatter plots from different models, or from the same classifier explained on different output scales, can't be compared by y-axis height.
- Look at categorical features with care. A feature with a few values draws vertical stripes. Read each stripe's center and spread. The trend line idea doesn't apply.
- Features that were scaled before modeling. The x-axis shows
.data, which is whatever you passed to the explainer. If you passed standardized values, the axis shows standardized values. In the diabetes dataset, all features are already centered and scaled, which is whybmiranges around zero and not in real BMI units.
Common misreadings
The scatter plot describes the model. It does not describe the world.
- A rising trend is not a causal effect. It says the model gives higher predictions when the feature is high. The model may do that because the feature is a proxy for something else.
- Correlated features share credit. If two features carry the same signal, each scatter plot may show only part of the effect, and which one gets more can change between model fits.
- Sparse regions can mislead. Use the histogram to see where data is thin. With interventional background data, the explainer evaluates feature combinations that never occur in the data, and the model's behavior there is unconstrained.
- The coloring feature is a hint. Confirm an interaction with interaction values or by testing the model directly. Don't conclude it from the colors alone.
Exercise
In a SHAP scatter plot for a feature, the dots form a clear rising trend, but at any given x the dots spread over a wide vertical range. Coloring by a second feature separates the dots into a high band and a low band. What does this tell you, and what would you conclude if the colors were mixed instead?
Show answer
The rising trend shows the model gives higher predictions as the feature increases, on average. The wide vertical spread shows the effect is not the same in every row. Because the colors separate cleanly into bands, the second feature changes how much the first feature contributes, so there is an interaction between them. If the colors were mixed, the second feature would not explain the spread. The spread would then come from another feature, or from correlated features sharing credit. You would need to try other coloring features or check interaction values to find the cause.
Exercise
Write code that computes, for the bmi feature of the sv object above, the average SHAP value in each of five quantile bins of bmi. Why is this different from a partial dependence curve?
Show answer
Use bmi = sv[:, "bmi"], build df = pd.DataFrame({"bmi": bmi.data, "shap": bmi.values}), add df["bin"] = pd.qcut(df["bmi"], 5), and call df.groupby("bin", observed=True)["shap"].mean(). This differs from partial dependence because it averages contributions measured on the real rows, relative to the baseline, and it can be paired with the per-bin standard deviation to expose interaction spread. Partial dependence sets the feature to each grid value for every row and averages the model's predictions, which hides the spread and sits on the prediction scale.