Sub topic 2
Background data: what it means to remove a feature
This chapter assumes you can train a scikit-learn style model, use pandas and NumPy, and know the idea behind Shapley values from the previous chapter. It covers what "removing a feature" means for a model, and why the answer depends on a dataset you choose.
The problem: models cannot drop inputs
Shapley values compare a model's output with and without a feature. A trained model has a fixed number of inputs, though. A gradient boosting model trained on 10 columns cannot accept 9. If you leave a column out, it fails or returns nonsense.
SHAP solves this by replacing the feature's value instead of deleting the column. The feature is "removed" when its value is swapped for values drawn from a reference dataset. This reference dataset is the background data.
Masking with background data
Take the brute-force code from the previous chapter. It used one baseline row, [0, 0, 0], and built each coalition like this:
z = [x[i] if i in subset else baseline[i] for i in range(n)]Features in the coalition keep the value from the row being explained. Features outside it take the value from the background. This is called masking.
With a real dataset, one baseline row is usually a poor choice. SHAP instead uses many background rows. For each coalition, it fills the masked features from each background row, runs the model on every resulting input, and averages the predictions. The coalition's value is therefore an expected prediction:
- Features in the coalition are fixed to the explained row's values.
- Features outside it vary over the background data.
- The model output is averaged over those background rows.
The following code makes this concrete. It masks one feature by hand:
import numpy as np
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]]
background = X.iloc[:100]
# Coalition = {"bmi"}: keep bmi from the row, vary everything else.
masked = background.copy()
masked["bmi"] = row["bmi"].iloc[0]
print(model.predict(masked).mean()) # value of the coalition {bmi}
print(model.predict(background).mean()) # value of the empty coalition
print(model.predict(row)[0]) # value of the full coalitionThe first number is the expected prediction when only bmi is known. The second is the expected prediction when nothing is known. The third is the actual prediction. SHAP's job is to split the gap between the second and third numbers across features.
Choosing a background dataset
The background data defines what "typical" means. It sets the baseline, which the next chapter covers. A different background gives different SHAP values for the same row and model.
Practical guidance:
- Use a sample of training data. It represents the inputs the model was built for.
- Keep it small enough to run fast. Cost grows with the number of background rows for model-agnostic methods. A few hundred rows is common.
- Sample, don't take the first rows. The first rows of a file may be sorted by date or class.
X.sample(100, random_state=0)avoids that. - Summarize if needed.
shap.kmeans(X, 10)compresses the data into weighted cluster centers. - Match the question. To ask why a prediction differs from other high-risk cases, use only high-risk rows as the background.
Background data and tree models
TreeExplainer can work without a background dataset. By default it uses the training statistics stored in the tree, so no background is passed. Passing a background dataset changes the method to an "interventional" calculation, which follows the masking description in this chapter. Model-agnostic explainers always require one.
import shap
background = X.sample(100, random_state=0)
explainer = shap.Explainer(model.predict, background)
sv = explainer(X.iloc[:5])
print(sv.base_values[:2])The base value printed here is the average prediction over the 100 background rows.
Common mistakes
| Mistake | Effect |
|---|---|
| Background drawn from a different population than the one explained | The baseline and all attributions describe the wrong comparison |
| Very small background | Noisy values that change from run to run |
| Background containing the rows being explained | Usually harmless, but it can bias the baseline toward them |
| Forgetting that masked mixes can be unrealistic | The model is evaluated on rows that never occur in real data |
The last row matters. Mixing one row's values with another row's values can produce combinations such as a very young patient with a very high age-related score. The model's response to those rows is part of the explanation. The limitations chapter returns to this.
Exercise
You explain the same row with two backgrounds: 100 random training rows, and only the 20 highest-risk training rows. Will the baseline and the SHAP values be the same? Explain why.
Show answer
No. The baseline is the average prediction over the background, so the high-risk background gives a higher baseline. SHAP values split the gap between the prediction and that baseline. The gap is smaller with the high-risk background, so the contributions change. Each answers a different question: why this prediction differs from a typical row, versus why it differs from a typical high-risk row.
Exercise
In the manual masking example, which of the three printed numbers is the baseline, and which equals the model's prediction for the row?
Show answer
The second number, the mean prediction over the unmasked background, is the baseline (the empty coalition). The third number, the model's prediction for the row, is the value of the full coalition.