Sub topic 2
Background data: what it means to remove a feature
This chapter assumes you can train and call a scikit-learn style model, use basic NumPy and pandas, and have read the previous chapter on Shapley values. Here you will learn how SHAP turns "leave this feature out" into something a trained model can handle, and why that choice changes your results.
The problem: models cannot take a missing input
A Shapley value for feature i compares the model's output with and without that feature, averaged over many combinations of the other features. That needs a prediction made from only some features. A trained model such as GradientBoostingRegressor always expects every column, so you cannot pass it a row with a feature missing.
SHAP handles this by simulating removal. For each feature you want to remove, it substitutes a value taken from a background dataset. The background dataset is a sample of rows that represents "typical" inputs. The model is then run on the patched row. Because there are many background rows, SHAP runs the model on many patched rows and averages the outputs.
For a set S of features that keep the explained row's values, the value function is:
v(S) = average over background rows b of f(x with features in S kept, all other features taken from b)
The Shapley formula from the previous chapter is applied to this v(S). Nothing else changes. The background data only defines what "absent" means.
A worked example with explicit background rows
The function below computes exact Shapley values, but its value function uses a background matrix instead of a single baseline row. It uses the same toy model as before, f(z) = 2*z[0] + z[1]*z[2], written to accept many rows at once.
from itertools import combinations
from math import factorial
import numpy as np
def f(Z):
return 2 * Z[:, 0] + Z[:, 1] * Z[:, 2]
def shapley_with_background(f, x, background):
x = np.asarray(x, dtype=float)
B = np.asarray(background, dtype=float)
n = len(x)
def value(subset):
Z = B.copy()
cols = sorted(subset)
if cols:
Z[:, cols] = x[cols] # keep these features from x
return f(Z).mean() # average over background rows
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(total)
return phi, value(set())
x = [1, 2, 3]
single = [[0, 0, 0]]
several = [[0, 0, 0], [2, 2, 0], [0, 4, 2]]
for name, bg in [("single zero row", single), ("three rows", several)]:
phi, base = shapley_with_background(f, x, bg)
print(name, [round(p, 3) for p in phi], "baseline", round(base, 3))
print(" sum check:", np.isclose(base + sum(phi), f(np.array([x]))[0]))Running it prints:
single zero row [2.0, 3.0, 3.0] baseline 0.0
sum check: True
three rows [0.667, -0.667, 4.0] baseline 4.0
sum check: TrueThe same row x and the same model give different attributions. With the zero background, feature 1 gets credit of 3.0. With the three-row background, it gets -0.667. Neither answer is wrong. They answer different questions: "why is this prediction higher than the prediction at all zeros?" versus "why is it higher than the average prediction over these three rows?"
In both cases the baseline plus the SHAP values equals the prediction. This is the additivity property, which a later chapter covers in detail.
The background sets the baseline
With no features kept, v(∅) is just the average model output over the background rows. This is the baseline (the expected value). In the three-row example it is (0 + 4 + 8) / 3 = 4.0. Changing the background changes this number, and every SHAP value shifts so that the total still reaches the prediction.
In the library you can check this directly. The example below wraps the diabetes model with an explicit masker object and compares the baseline to the model's mean prediction over the background rows.
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)
background = X.iloc[:100]
masker = shap.maskers.Independent(background, max_samples=100)
explainer = shap.Explainer(model.predict, masker)
sv = explainer(X.iloc[:5])
print(np.isclose(sv.base_values[0], model.predict(background).mean(), atol=1e-4))This should print True. The Independent masker is the piece that does the replacement. The argument max_samples caps how many background rows are used, which matters for cost.
Common ways to supply the background
The right choice depends on model type and dataset size. Use this table as a starting point.
| Option | What it is | Typical use |
|---|---|---|
| Training data sample | `shap.sample(X_train, 100)` draws random rows | Default choice for most tabular models |
| Whole training set | Pass all rows | Small datasets, or when exactness matters more than time |
| Summarized data | `shap.kmeans(X_train, 10)` returns weighted cluster centers | Large data with model-agnostic explainers |
| Single reference row | One chosen row, such as a median customer | You want a specific comparison, such as "versus the typical applicant" |
| No background | `TreeExplainer(model)` with no `data` argument | Trees only, using the model's own training-set statistics |
Cost grows roughly linearly with the number of background rows, because each coalition is evaluated on every one. A background of 100 rows is usually enough to estimate a stable average. If the baseline moves noticeably when you resample, increase the size.
Two ways to define "removed"
SHAP supports two views of what removing a feature should mean.
- Interventional (marginal). Replace the feature with values from the background, ignoring any relationship with the features you kept. This is what
Independentdoes. It breaks the correlation structure, and it asks what the model does when this feature is forced to a value. - Conditional. Replace the feature with values that are plausible given the features that remain, for example by sampling only background rows similar to
xon the kept features. This respects correlation, but it is harder to estimate and it spreads credit between correlated features differently.
For tree models the choice appears as the feature_perturbation argument of TreeExplainer. The value "interventional" uses the background you pass in data. The value "tree_path_dependent" needs no background and approximates the conditional view using how many training samples went down each branch. If you pass data without setting the argument, the interventional method is used, and without data the tree-path method is used.
Edge cases to watch
- Background that does not match deployment. If you explain a model with training rows but the explained rows come from a different population, the baseline describes the wrong group. Choose a background that matches the comparison you want to make.
- Too small or unrepresentative. A background of five rows can put the baseline far from the real average prediction. Compare the baseline against
model.predict(X_train).mean()as a quick sanity check. - Categorical features. Encoded integers get averaged and mixed freely by the masker. A patched row can contain a category combination that never occurs. Check that your encoding behaves sensibly when values come from different rows.
- Rows in the background equal to the explained row. This is harmless, but it means that row's own contribution can look small, because part of the baseline already sits at its values.
- Duplicates and weights.
shap.kmeansreturns weighted centers. Pass the result directly to the explainer so the weights are used. Do not convert it to a plain array.
Exercise
You explain one loan application using a background of 100 random training rows and get a baseline of 0.12 (the model's predicted default probability). A colleague uses only rows from applicants with a high income and gets a baseline of 0.05. The explained prediction is 0.30 in both cases. What happens to the sum of the SHAP values in each case, and why do the individual values differ?
Show answer
The sum is 0.30 - 0.12 = 0.18 in your case and 0.30 - 0.05 = 0.25 in your colleague's case. Both sets of values add up to the prediction minus their own baseline. The individual values differ because each background defines "feature absent" differently. For the colleague, income is replaced by high-income values, so the application's income contributes less in the same direction than it does against the mixed background. The two explanations answer different comparison questions.
Exercise
In shapley_with_background, what would value(set()) return if the background contained only the explained row x itself, and what would the SHAP values be?
Show answer
Every patched row equals x, so value(set()) is f(x), and the baseline equals the prediction. Every difference value(s | {i}) - value(s) is zero, so all SHAP values are zero. The explanation has nothing to attribute, because the comparison point is identical to the explained row.