Sub topic 3
The baseline value
This chapter assumes you can train a scikit-learn model and read a pandas DataFrame. It also assumes you have met the idea of a Shapley value, where a prediction is split into one contribution per feature. Here we look at the number every SHAP explanation is measured against: the baseline.
What the baseline is
A SHAP value never says "this feature added 5 to the prediction" on its own. It says "this feature moved the prediction 5 away from the baseline." The baseline is the model's output when no feature values are known, so it is the starting point of every explanation.
In the Shapley formulation, the baseline is the value of the empty coalition. That is the case where every feature has been "removed". The previous chapter covered how removal works: removed features are replaced by values drawn from a background dataset. The baseline is the model's average output over those substituted values.
In the SHAP library this number appears in two places:
explainer.expected_valueis the baseline as a single number (or one number per output for multi-output models).explanation.base_valuesholds the same baseline for each explained row.
The baseline is a property of the background
The baseline depends on the background data and on the model. It is not a fixed property of the model alone. Change the background and you change the baseline, and therefore every SHAP value.
The brute-force function below uses a single reference row as the background. It is the same function used earlier in this tutorial, but it rounds its output so floating-point noise does not hide the result. We explain the same input against two different baselines.
from itertools import combinations
from math import factorial
def shapley_values(f, x, baseline):
n = len(x)
def value(subset):
z = [x[i] if i in subset else baseline[i] for i in range(n)]
return f(z)
phi = []
for i in range(n):
others = [j for j in range(n) if j != i]
total = 0.0
for size in range(n):
for subset in combinations(others, size):
s = set(subset)
weight = factorial(len(s)) * factorial(n - len(s) - 1) / factorial(n)
total += weight * (value(s | {i}) - value(s))
phi.append(round(total, 6))
return phi
f = lambda z: 2 * z[0] + z[1] * z[2]
x = [1, 2, 3]
for baseline in ([0, 0, 0], [1, 1, 1]):
phi = shapley_values(f, x, baseline)
print(baseline, "f(baseline) =", f(baseline), "phi =", phi,
"sum =", sum(phi), "f(x) - f(baseline) =", f(x) - f(baseline))The output is:
[0, 0, 0] f(baseline) = 0 phi = [2.0, 3.0, 3.0] sum = 8.0 f(x) - f(baseline) = 8
[1, 1, 1] f(baseline) = 3 phi = [0.0, 2.0, 3.0] sum = 5.0 f(x) - f(baseline) = 5With the second baseline, feature 0 gets zero credit because its value already equals the reference value, so there is nothing to explain. The prediction f(x) is 8 in both runs. Only the question changed: "why 8 rather than 0?" versus "why 8 rather than 3?"
Two ways to compute the baseline
For tree models, TreeExplainer offers two settings for feature_perturbation. They define the baseline differently.
| Setting | Background | Baseline |
|---|---|---|
| `"tree_path_dependent"` (default when no `data` is given) | None. It uses the sample counts stored in each tree node. | Mean model output over the training data, weighted by how many training rows reached each leaf. |
| `"interventional"` (used when you pass `data`) | The rows you supply. | Mean model output over the background rows. |
Model-agnostic explainers such as Permutation and Kernel always need a background, because they have no tree structure to read counts from. In that case the baseline is the mean prediction over the background rows. A masker built from that background substitutes values for the "removed" features.
Checking the baseline in code
The next example fits a model and builds two explainers with different backgrounds. For each one it checks two things: that the baseline equals the mean prediction over its background, and that the baseline plus the row's SHAP values reproduces the model's prediction.
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)
row = X.iloc[[0]]
pred = model.predict(row)[0]
backgrounds = {
"first 100 rows": X.iloc[:100],
"rows with y below median": X[y < y.median()],
}
for name, bg in backgrounds.items():
explainer = shap.TreeExplainer(
model, data=bg, feature_perturbation="interventional"
)
base = np.ravel(explainer.expected_value)[0]
sv = explainer(row)
print(name)
print(" baseline:", round(float(base), 2))
print(" mean prediction on background matches:",
np.isclose(base, model.predict(bg).mean(), atol=1e-3))
print(" baseline + sum(SHAP) == prediction:",
np.isclose(base + sv.values[0].sum(), pred, atol=1e-3))Both checks print True for both backgrounds. The baselines differ, though: the low-target background gives a lower baseline. The same row therefore receives larger positive contributions when it is compared with low-target rows than when it is compared with a typical sample.
Without a data argument, shap.TreeExplainer(model) uses the default tree-path-dependent setting. Its baseline is close to the mean prediction over the training data.
Choosing a background on purpose
The default question is "why is this prediction different from the average prediction?" Other questions need other backgrounds.
- A representative sample of the training data. This is the usual choice, and the baseline then means "typical output." A random sample of 100 to 1000 rows is normally enough, because cost grows with background size.
- A specific subgroup. If you ask "why was this loan scored higher than the approved applicants?", use the approved applicants as the background. The explanation is then a contrast against that group.
- A single reference row. This gives a point-to-point comparison, like the
[1, 1, 1]example above. It is easy to interpret but sensitive to the one row you picked. - Rows that are realistic for the model. Background rows should be plausible inputs. A background of impossible combinations produces baselines and attributions the model never saw during training.
Do not summarize the background with a single row of column means as a shortcut. For a nonlinear model, f(mean of x) is generally not the same as the mean of f(x). The baseline would then no longer be the model's average output.
Reading the baseline in a plot
Waterfall and force plots start at the baseline and end at the prediction. In a waterfall plot, E[f(X)] at the bottom is the baseline and f(x) at the top is the prediction. Each bar in between is one SHAP value. Bars pointing right raise the value from the baseline and bars pointing left lower it.
Read the baseline before you read the bars. A prediction of 180 means different things when the baseline is 150 and when it is 50. Also check that the baseline matches the population you intended to compare against.
Common mistakes
- Assuming the baseline is zero. For regression it is the mean output. For classifiers explained in log-odds, a baseline of 0 would mean a 50% probability, which is rare. The baseline is usually negative when the positive class is uncommon. A later chapter covers output units.
- Comparing SHAP values from different backgrounds. Values computed against different baselines answer different questions, so they are not directly comparable.
- Using a tiny background. A handful of rows gives a noisy baseline and noisy values for any model that is not close to linear.
- Confusing the baseline with a decision threshold. A baseline above or below your classification cutoff says nothing about which class is predicted. Only the final prediction,
baseline + sum of SHAP values, is compared with a threshold. - Forgetting that the baseline is shared. Every row explained by one explainer shares the same baseline, which is why
base_valuesis constant across rows for these models. This is what lets you compare SHAP values between rows.
Summary
- The baseline is the model's mean output over the background data, and it is the starting point for every explanation.
- Changing the background changes the baseline and all SHAP values. It changes the question being asked, not just the numbers.
TreeExplainerwithoutdatauses training-data sample counts. Withdata, and the interventional setting, it uses your background rows.- You can check any baseline by comparing
explainer.expected_valuewithmodel.predict(background).mean().
Exercise
A regression model has predictions averaging 200 over the full training set, and averaging 120 over a subgroup of "low-risk" customers. A customer's prediction is 150. What is the sum of their SHAP values if you explain with the full training set as background, and what is it if you use the low-risk subgroup? Which explanation would you use to ask "why is this customer scored higher than low-risk customers?"
Show answer
With the full training set as background the baseline is 200, so the SHAP values sum to 150 - 200 = -50. With the low-risk background the baseline is 120, so they sum to 150 - 120 = +30. Use the low-risk background to ask why this customer scores higher than low-risk customers, because the explanation is measured against that group's average.
Exercise
You build a TreeExplainer with a background of 50 rows. You find that explainer.expected_value differs from y.mean(), the mean of the target column. Is this a bug? What would you compare it with instead?
Show answer
It is not a bug. The baseline is the mean model output over the background, not the mean of the true target. Compare explainer.expected_value with model.predict(background).mean(). These should match closely for the interventional setting.