Sub topic 8
Working with the Explanation object
This chapter assumes you can train a scikit-learn style model, use pandas and NumPy, and understand that SHAP values add up to the gap between a prediction and a baseline. The goal here is to handle the object that the shap library returns, so you can slice it, check it, and pass it to plots without surprises.
What the Explanation object holds
Calling an explainer on data returns a shap.Explanation. It bundles everything you need to describe a set of predictions. You will use these attributes most often:
| Attribute | Meaning | Typical shape |
|---|---|---|
| `values` | SHAP values, one per row and feature | `(n_samples, n_features)` |
| `base_values` | Baseline (expected) value for each row | `(n_samples,)` |
| `data` | The feature values that were explained | `(n_samples, n_features)` |
| `feature_names` | Column names | `(n_features,)` |
The key property is local accuracy. For each row, base_values[i] + values[i].sum() equals the model output for that row, in the model's output units.
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)
model = GradientBoostingRegressor(random_state=0).fit(X, y)
explainer = shap.TreeExplainer(model)
sv = explainer(X)
print(type(sv))
print(sv.values.shape) # (n_samples, n_features)
print(sv.base_values.shape) # (n_samples,)
print(sv.data.shape) # (n_samples, n_features)
print(sv.feature_names)
print(np.isclose(sv.base_values[0] + sv.values[0].sum(),
model.predict(X.iloc[[0]])[0], atol=1e-4))The last line should print True. If you pass a pandas DataFrame, the column names are stored in feature_names, which is why plots show readable labels.
Why base_values has one entry per row
The baseline is the same number for every row in a simple regression model, so a length-n_samples array may look redundant. The library keeps one entry per row so that the same structure works when the baseline varies. That happens with some multi-output models and with explainers that compute a row-specific expected value. Slicing a row then carries its own baseline along, and plots never need a separate baseline argument.
Indexing and slicing
An Explanation behaves like a NumPy array with labels. Slicing returns another Explanation, with values, base_values, data and feature_names kept consistent.
row = sv[0] # one prediction
first_ten = sv[:10] # first ten rows
bmi = sv[:, "bmi"] # one feature across all rows
subset = sv[:, ["bmi", "bp"]] # several features by name
print(row.values.shape) # (n_features,)
print(row.base_values) # a scalar for this row
print(bmi.values.shape) # (n_samples,)
print(subset.feature_names) # ['bmi', 'bp']Selecting a feature by name only works when the explanation has feature names. If you explained a plain NumPy array, use integer positions, or pass a DataFrame so names are kept.
You can also select rows with a boolean mask. This is useful for explaining a subgroup:
high_bmi = sv[(X["bmi"] > 0.05).to_numpy()]
print(high_bmi.values.shape)Summaries and operations
The Explanation object has helper methods on its attributes. The ones used most are listed here.
sv.abs.mean(0)returns an Explanation with the mean absolute SHAP value per feature. This is the quantity the bar plot draws.sv.values.mean(0)returns the signed mean. Positive and negative effects cancel here, so it is rarely a good importance measure.sv.abs.max(0)returns the largest absolute effect of each feature.
importance = sv.abs.mean(0)
order = np.argsort(-importance.values)
for i in order[:5]:
print(sv.feature_names[i], round(float(importance.values[i]), 3))Because the result keeps feature_names, you can pass it straight to shap.plots.bar(importance).
Plain arrays versus the Explanation
Older code calls explainer.shap_values(X), which returns a bare NumPy array (or a list of arrays for some classifiers) and a separate explainer.expected_value. The newer call explainer(X) returns an Explanation. Prefer the new form for three reasons:
- The values, baseline, data and names cannot drift apart.
- The
shap.plotsfunctions accept the object directly. - Slicing keeps everything aligned.
If you must convert, use sv.values and sv.base_values. When mixing the two styles, check the shapes before you trust any plot.
Common errors
- Passing the wrong thing to a plot.
shap.plots.waterfallneeds a single row, sosv[0], notsv. Passing the whole object raises an error about the shape.shap.plots.beeswarmneeds many rows. - Missing feature names. If
feature_namesisNone, plots label featuresFeature 0,Feature 1and so on. Explain a DataFrame, or setsv.feature_namesyourself. - Mismatched data. If you build an Explanation by hand,
valuesanddatamust have the same shape. Mixing values from one dataset with data from another gives plots with misleading colors and no error. - Skipping the additivity check. If the sum does not match the model output, the units differ. This often happens with classifiers, where SHAP values may be in log-odds while
predict_probais in probability. A later chapter covers output units. - Assuming a 3-D shape. Some multi-class models return
valueswith shape(n_samples, n_features, n_classes). Select one class withsv[..., k]before plotting.
Building an Explanation yourself
Sometimes you compute values with another tool, or you want to edit them, for example to merge several features into one group. You can construct an Explanation directly.
grouped_values = np.column_stack([
sv.values[:, [0, 1]].sum(axis=1), # age + sex combined
sv.values[:, 2:].sum(axis=1), # all remaining features
])
grouped = shap.Explanation(
values=grouped_values,
base_values=sv.base_values,
data=np.column_stack([X["age"], X["bmi"]]),
feature_names=["age + sex", "other features"],
)
print(grouped.values.shape)
print(np.allclose(grouped.base_values + grouped.values.sum(1),
sv.base_values + sv.values.sum(1)))Summing SHAP values over a group of features is valid because attributions are additive. The sum is the joint contribution of the group. The data array here is only a placeholder for display, so choose a value that makes sense for your plot. The check on the last line confirms the grouped version still reproduces each prediction.
Exercise
You compute sv = explainer(X) for a regression model with 500 rows and 8 features. What shapes do sv.values, sv.base_values and sv[:, "age"].values have? Then write one expression that checks local accuracy for row 3, assuming model.predict returns the same units as the explainer.
Show answer
sv.values has shape (500, 8), sv.base_values has shape (500,), and sv[:, "age"].values has shape (500,). The check is np.isclose(sv.base_values[3] + sv.values[3].sum(), model.predict(X.iloc[[3]])[0], atol=1e-4), which should be True.
Exercise
A colleague calls shap.plots.waterfall(sv) and gets a shape error. What is the cause, and what is the fix?
Show answer
The waterfall plot explains one prediction, but sv holds many rows. Pass a single row, for example shap.plots.waterfall(sv[0]).