Sub topic 8
Working with the Explanation object
This chapter assumes you can train a scikit-learn style model and use pandas and NumPy. It also assumes you know that SHAP values split a prediction into a baseline plus one contribution per feature. Here you learn the container that holds those numbers and how to slice it.
What the object contains
Calling an explainer on data, as in explainer(X), returns a shap.Explanation. It bundles everything you need to explain and plot a prediction. Older code used raw NumPy arrays from explainer.shap_values(X). The Explanation object replaces them, and all shap.plots functions accept it.
| Attribute | Meaning | Shape for a regressor |
|---|---|---|
| `values` | SHAP values | `(n_samples, n_features)` |
| `base_values` | Baseline for each row | `(n_samples,)` |
| `data` | Original feature values | `(n_samples, n_features)` |
| `feature_names` | Column names | list of `n_features` strings |
Keeping data next to values lets plots color points by feature value and label the axes without extra arguments.
Inspecting and slicing
The example below builds the object, then slices it by row, by feature name and by summary operation.
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)
sv = shap.TreeExplainer(model)(X)
print(type(sv).__name__)
print(sv.values.shape, sv.base_values.shape, sv.data.shape)
print(sv.feature_names)
row = sv[0] # one prediction
print(row.values.shape) # (n_features,)
bmi = sv[:, "bmi"] # one feature across all rows
print(bmi.values.shape) # (n_samples,)
print(sv.abs.mean(0).values) # mean |SHAP| per featureIndexing works like a NumPy array, with two additions. You can use a feature name in the column position, and you can chain operations such as .abs and .mean(0). Each slice is itself an Explanation, so you can pass it straight to a plot. A single-row slice feeds a local plot such as waterfall. A single-column slice feeds scatter.
Checking additivity
The object lets you test local accuracy directly. For every row, base_values + values.sum(axis=1) should equal the model output.
reconstructed = sv.base_values + sv.values.sum(axis=1)
print(np.allclose(reconstructed, model.predict(X), atol=1e-4))If this check fails, the cause is usually one of two things. Either you explained a different model output than the one you compare against, or the explainer approximated the values.
Common errors
- Classifiers add an axis. Many classifiers give
valuesthe shape(n_samples, n_features, n_classes). Select one class first, for examplesv[..., 1], before using plots that expect two dimensions. - Plain arrays lose names. If you pass a NumPy array instead of a DataFrame,
feature_namesisNone. Slicing by name then fails. Use a DataFrame or passfeature_namesyourself. - Explaining everything is slow. For model-agnostic explainers, slice the input first, for example
explainer(X.iloc[:200]). Cost grows with rows. - Units follow the model output. A tree classifier may return log-odds, not probabilities. The Explanation records contributions in whatever units the explainer used.
Exercise
Using sv from this chapter, write one expression that returns the SHAP values of the feature "bmi" for only the first 50 rows, and say what shape the result has.
Show answer
sv[:50, "bmi"].values returns a one-dimensional array of shape (50,). The row slice :50 keeps 50 rows, and the feature name selects a single column, which removes the feature axis.