Sub topic 9
Explaining a single prediction
This chapter assumes you can train a scikit-learn style model and use pandas. It also assumes you know that SHAP values add up to the prediction minus the baseline. That identity was covered in the earlier chapters on baselines and additivity. Here you apply it to one row at a time.
What a local explanation answers
A local explanation answers one question: why did the model output this value for this row, instead of the baseline value? The baseline is the average prediction over the background data. Each feature gets a signed number. Positive numbers push the prediction above the baseline, and negative numbers push it below. All the numbers together account for the full gap.
The left-to-right order in the diagram is a drawing convention. Shapley values average over all orderings of the features, so no feature really "comes first".
Setting up one row
The examples reuse the gradient boosting model on the diabetes data. This block is self-contained.
import numpy as np
import shap
import matplotlib.pyplot as plt
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)
row = sv[0]
print(row.base_values) # baseline for this row
print(row.values) # one SHAP value per feature
print(row.data) # the feature values that were explained
print(row.feature_names)Indexing an Explanation with an integer gives a one-row Explanation. It holds the three things every local plot needs: the baseline (base_values), the contributions (values), and the feature values (data).
Reading the numbers without a plot
Before you draw anything, it helps to see the raw ranking that the plots visualize.
order = np.argsort(-np.abs(row.values))
for i in order[:5]:
print(f"{row.feature_names[i]:>4} = {row.data[i]:+.3f} -> SHAP {row.values[i]:+.2f}")
pred = model.predict(X.iloc[[0]])[0]
print(row.base_values + row.values.sum(), pred)Each line pairs a feature's value with its contribution. For example, a line might show that a high bmi pushed the predicted disease progression up. The last line checks local accuracy: baseline plus the sum of contributions equals the model's prediction, up to floating-point error.
The waterfall plot
The waterfall plot is the standard local view.
shap.plots.waterfall(row, max_display=6, show=False)
plt.tight_layout()
plt.savefig("waterfall.png", dpi=150)
plt.close()Read it like this:
- The bottom of the plot shows
E[f(X)], the baseline. - Each bar is one feature. Its length is the SHAP value, and red means positive, blue means negative.
- Gray numbers beside the feature names are that row's feature values.
- The bars stack from the baseline upward, and the top of the stack shows
f(x), the prediction. - With
max_display=6, the five largest contributions are shown individually. A bottom row such as "5 other features" holds the summed SHAP value of the rest.
Features are sorted by absolute SHAP value for this row. The order changes from row to row, and it is not an order of global importance.
The force plot
The force plot shows the same information in a single horizontal band.
shap.initjs() # only needed in notebooks, to load the JavaScript renderer
shap.plots.force(row)Features in red push the prediction to the right (higher), and features in blue push it to the left (lower). The baseline and the final prediction mark the two ends of the band. Outside a notebook, pass matplotlib=True to get a static figure for a single row:
shap.plots.force(row, matplotlib=True, show=False)
plt.savefig("force.png", dpi=150, bbox_inches="tight")
plt.close()The force plot is compact, but labels overlap once more than about six features matter. Prefer the waterfall plot for reading and for reports, and use force plots when you want to compare many rows by stacking them.
A bar plot of one row
A local bar plot is the simplest option. It has no baseline-to-prediction stacking, only signed bars.
shap.plots.bar(row, max_display=6, show=False)
plt.tight_layout()
plt.savefig("local_bar.png", dpi=150)
plt.close()Passing a single row gives a local plot. Passing the whole Explanation gives the global mean-absolute plot covered in the next chapter. The same function name handles both, so check which object you passed.
| Plot | Shows baseline and prediction | Best for | Weakness |
|---|---|---|---|
| Waterfall | Yes, both ends labeled | Careful reading of one row | One row per figure |
| Force | Yes, as the ends of the band | Compact display, stacking many rows | Labels overlap with many features |
| Local bar | No | Quick ranking of contributions | Does not show how the total is built |
Interpreting a row correctly
A SHAP value compares this row to the background data. It is not a statement about the feature alone. If bmi has SHAP value +20 for a patient, the model's output is 20 units higher than it would be if bmi were drawn from the background distribution, with the other features' roles accounted for in the Shapley average.
Several consequences follow:
- The baseline depends on your background data. Changing the background sample changes the baseline and every SHAP value. Two explanations are comparable only if they use the same background.
- Units are the model's output units. For this regression model, SHAP values are in units of the target. For a classifier, they are often log-odds, which the chapter on output units covers.
- Small SHAP values do not mean a feature is unimportant. They mean the feature barely moved this row away from the baseline. A feature can matter a great deal for other rows.
- A near-zero value can hide offsetting effects. The explanation is per feature. If two correlated features carry the same signal, the credit is split between them.
Comparing two rows
A common task is explaining why two predictions differ. Subtract the SHAP vectors, because both rows share the same baseline when the explainer is the same.
a, b = sv[0], sv[1]
diff = a.values - b.values
order = np.argsort(-np.abs(diff))[:3]
for i in order:
print(f"{a.feature_names[i]:>4}: {diff[i]:+.2f}")
print(np.isclose(diff.sum(),
(a.base_values + a.values.sum()) - (b.base_values + b.values.sum())))The differences sum to the gap between the two predictions. This is a valid comparison for tree explainers with a fixed background. It does not tell you which feature "caused" the gap in a causal sense.
Common mistakes
- Reading bar length as a feature value. The bar length is the contribution. The gray number is the feature value.
- Explaining the wrong output. For a classifier,
sv[0]may hold values for several classes. Select the class you mean before plotting, for examplesv[0, :, 1]. - Mixing explainers. Values from
TreeExplainerand from a permutation explainer use different backgrounds and masking rules. Do not subtract them. - Trusting rounded plots. Plots round to two decimals, so check
row.valuesdirectly when a decision depends on small differences.
Exercise
A waterfall plot for one row shows a baseline of 150 at the bottom and a prediction of 210 at the top. The five largest bars are +40, +25, -15, +8 and -3, and one bottom row reads "5 other features". What is the SHAP value of that bottom row, and what does it mean?
Show answer
The visible bars sum to 40 + 25 - 15 + 8 - 3 = 55. The total gap is 210 - 150 = 60, so the bottom row is +5. It is the summed SHAP value of the five hidden features, which together pushed the prediction up by 5. Local accuracy guarantees that the baseline plus all contributions equals the prediction.
Exercise
Why can you compare the SHAP vectors of two rows by subtracting them, but not the SHAP vectors from a TreeExplainer and a permutation explainer built on a different background sample?
Show answer
Within one explainer and one background, both rows share the same baseline, so the difference of their SHAP vectors sums to the difference of their predictions. Two explainers with different backgrounds define "removing a feature" differently and have different baselines, so their values answer different questions and cannot be subtracted meaningfully.