Sub topic 12
Output units: raw margins, log-odds and multi-class outputs
This chapter assumes you can train a scikit-learn style classifier and have read the earlier chapters on baselines and additivity. A SHAP value has no units of its own. It is measured in whatever units the explained model output uses. This chapter shows how to find out which output you are explaining, how to convert it, and how multi-class models change the shape of the results.
SHAP values inherit the output's units
Additivity says that, for one row, baseline plus the sum of SHAP values equals the model output being explained. The baseline and every SHAP value therefore share that output's units. The table lists the common cases.
| Model and explainer | Explained output | Units of SHAP values |
|---|---|---|
| Any regressor | Prediction | Target units (dollars, days, and so on) |
| `GradientBoostingClassifier`, binary, `TreeExplainer` | Raw score (`decision_function`) | Log-odds of class 1 |
| XGBoost or LightGBM binary classifier, `TreeExplainer` | Raw margin | Log-odds of class 1 |
| `RandomForestClassifier`, `TreeExplainer` | Class probabilities | Probability, one output per class |
| Any classifier, `shap.Explainer(model.predict_proba, ...)` | Class probabilities | Probability, one output per class |
| Same, with `link=shap.links.logit` | Logit of the probability | Log-odds |
A raw margin is the model's score before the final squashing function turns it into a probability. For boosted trees the margin is the sum of all tree outputs plus an initial value. Log-odds are the natural logarithm of p / (1 - p). A log-odds of 0 means a 50% probability. Positive values favor class 1.
The model output is a fixed property of the model and explainer pair. You cannot assume it is the probability just because the model has a predict_proba method. Check it every time.
Binary classifiers explained in log-odds
Tree boosting models add up tree outputs in margin space, so TreeExplainer explains the margin by default. This is fast and exact. The next example uses a binary scikit-learn gradient boosting classifier.
import numpy as np
import shap
from sklearn.datasets import load_breast_cancer
from sklearn.ensemble import GradientBoostingClassifier
X, y = load_breast_cancer(return_X_y=True, as_frame=True)
clf = GradientBoostingClassifier(random_state=0).fit(X, y)
explainer = shap.TreeExplainer(clf)
sv = explainer(X)
print(sv.values.shape) # (569, 30): one value per row and feature
raw = sv.base_values[0] + sv.values[0].sum()
margin = clf.decision_function(X.iloc[[0]])[0]
print(np.isclose(raw, margin, atol=1e-4)) # True: SHAP sums to the margin
prob = 1 / (1 + np.exp(-raw))
print(np.isclose(prob, clf.predict_proba(X.iloc[[0]])[0, 1], atol=1e-4)) # TrueThe first check passes against decision_function, not against predict_proba. The sigmoid function, 1 / (1 + exp(-z)), connects the two. It turns the margin into a probability.
The plots follow the same units. A waterfall plot for this model shows E[f(X)] and f(x) as log-odds. A bar of +0.8 for one feature means that feature pushed the log-odds up by 0.8. It does not mean the probability rose by 0.8.
Why you cannot convert each SHAP value to probability
The sigmoid is nonlinear, so you can only apply it to the total. If a feature contributes +1.0 log-odds, its probability effect depends on where the other features have already moved the margin.
- Near a margin of 0, the sigmoid is steep. A +1.0 step adds about 0.23 probability (from 0.50 to 0.73).
- Near a margin of 4, it is flat. A +1.0 step adds about 0.01 probability (from 0.982 to 0.993).
Applying the sigmoid to each SHAP value separately gives numbers that do not sum to anything meaningful. Convert the baseline and the total, and describe individual features in log-odds. For a rough sense of scale you can say that one log-odds unit is large near 50% and small near the extremes.
Explaining probabilities instead
Sometimes stakeholders want effects in percentage points. There are two ways to get them, and each has a cost.
- Use a model whose explained output is already a probability.
TreeExplaineron a scikit-learn random forest does this, because the forest averages the probabilities its trees produce. - Use a model-agnostic explainer on
predict_proba. Additivity then holds in probability space, but you pay the computational cost of sampling.
TreeExplainer can also explain the transformed output of a boosted model. You pass model_output="probability". This needs a background dataset and feature_perturbation="interventional", because the path-dependent method cannot handle the nonlinear transform. Prefer margins when you only need to understand the model. They are exact and cheaper.
Choosing a link for model-agnostic explainers
Model-agnostic explainers have a link argument. The explainer computes SHAP values for the function you give it. The link function then lets you present them on a different scale. With link=shap.links.logit, the explained quantity becomes the logit of the probability, so the values are in log-odds even though you passed a probability function.
def prob_class1(data):
return clf.predict_proba(data)[:, 1]
background = X.iloc[:100]
agnostic = shap.Explainer(
prob_class1, background, algorithm="permutation", link=shap.links.logit
)
sv_logit = agnostic(X.iloc[:5])
target = clf.decision_function(X.iloc[:5])
total = sv_logit.base_values + sv_logit.values.sum(axis=1)
print(np.allclose(total, target, atol=1e-3)) # should print TrueOne subtlety applies here. The baseline is the logit of the mean predicted probability over the background. It is not the mean of the log-odds. The two differ because the logit is nonlinear. As a result, the baseline can differ from the TreeExplainer baseline for the same model, and the individual values will differ slightly too. Both are valid decompositions of the same prediction. They answer slightly different questions.
Multi-class models: one explanation per class
A multi-class model has one output per class, so it has one set of SHAP values per class. In current versions of shap, the Explanation object has three dimensions: rows, features, and outputs. Earlier versions returned a Python list with one array per class. Check values.shape before writing indexing code.
from sklearn.datasets import load_iris
from sklearn.ensemble import RandomForestClassifier
Xi, yi = load_iris(return_X_y=True, as_frame=True)
rf = RandomForestClassifier(n_estimators=100, random_state=0).fit(Xi, yi)
sv_rf = shap.TreeExplainer(rf)(Xi)
print(sv_rf.values.shape) # (150, 4, 3): rows, features, classes
print(sv_rf.base_values.shape) # (150, 3): one baseline per class
reconstructed = sv_rf.base_values[0] + sv_rf.values[0].sum(axis=0)
print(np.allclose(reconstructed, rf.predict_proba(Xi.iloc[[0]])[0], atol=1e-4))
virginica = sv_rf[..., 2] # Explanation for class index 2 only
shap.plots.beeswarm(virginica)Each class has its own baseline. For a random forest it is the average predicted probability of that class over the background. For the forest, the three baselines sum to 1, and the three SHAP values of any one feature sum to 0 for every row. Probabilities must total 1, so a push toward one class is a push away from the others.
Plots accept only a one-output Explanation. Slice the class you want with sv[..., k] before plotting. A bar plot of the full three-dimensional object would be ambiguous.
For a multi-class boosted model, TreeExplainer explains the raw margin for each class. Those margins are log-odds in a softmax model, where the softmax function turns the per-class margins into probabilities that sum to 1. A margin is not a log-odds of that class against the rest. Only differences between class margins have a log-odds meaning.
Common mistakes with units
- Reading a log-odds waterfall as percentage points. Always read the axis label, and check whether the model type can produce a margin.
- Comparing SHAP magnitudes across models with different outputs. Values from a log-odds model and a probability model are not on the same scale.
- Comparing the SHAP values of different classes as if they were the same quantity. They describe different outputs, with different baselines.
- Passing
model.predictfor a classifier. It returns hard labels, so the SHAP values explain a step function and are mostly zero or noisy. - Forgetting that the baseline moves with the background data for model-agnostic explainers and for
TreeExplainerin interventional mode.
Exercise
A binary XGBoost classifier explained with TreeExplainer has a baseline of -1.2 and SHAP values for one row that sum to +2.0. What is the predicted probability of class 1, and why can you not say that the top feature, with a SHAP value of +0.9, raised the probability by 0.9?
Show answer
The raw margin is -1.2 + 2.0 = 0.8 in log-odds. The probability is the sigmoid of 0.8, which is 1 / (1 + exp(-0.8)), about 0.69. The SHAP value of +0.9 is in log-odds, and the sigmoid is nonlinear. The same +0.9 shifts the probability by different amounts depending on the margin at which it is applied, so it is not a probability change.
Exercise
You fit a RandomForestClassifier on a 4-class problem and call TreeExplainer on 200 rows. What shape do you expect for the values and the base values in a current shap version, and how do you plot a beeswarm for class 3 only?
Show answer
The values have shape (200, n_features, 4) and the base values have shape (200, 4). Slice one class with sv[..., 3], which gives a one-output Explanation, and then call shap.plots.beeswarm(sv[..., 3]). If the shape is a list of four arrays instead, you have an older version.