Skill Tracer
Skills › Scientific Agent Skills › shap › data-maskers.md

data-maskers.md

288 lines · skills/shap/references/data-maskers.md at 5f2bc03

Open on GitHub
1# Background Data and Maskers
2
3SHAP values are defined relative to a cooperative game. The background data and masker define what hidden features mean and therefore help define the question being answered. They are not merely performance parameters.
4

Background Data and Maskers

SHAP values are defined relative to a cooperative game. The background data and masker define what hidden features mean and therefore help define the question being answered. They are not merely performance parameters.

Raw lines 1 to 4
5## Start With the Estimand
6
7For a row `x`, an explanation decomposes a model output relative to a baseline:
8
9```text
10explained output = base value + sum(feature attributions)
11```
13The baseline and attributions depend on the reference distribution used when features are hidden.
15Examples of distinct questions:
17- **Population-relative:** Why is this prediction different from the training population?
18- **Current-production-relative:** Why is it different from recent production traffic?
19- **Control-relative:** Why is it different from a clinically meaningful reference cohort?
20- **Case-relative:** Why do two otherwise comparable cases receive different scores?
22These questions can produce different baselines, signs, magnitudes, and rankings. State the intended question before sampling background rows.

Start With the Estimand

For a row x, an explanation decomposes a model output relative to a baseline:

explained output = base value + sum(feature attributions)

The baseline and attributions depend on the reference distribution used when features are hidden.

Examples of distinct questions:

  • Population-relative: Why is this prediction different from the training population?
  • Current-production-relative: Why is it different from recent production traffic?
  • Control-relative: Why is it different from a clinically meaningful reference cohort?
  • Case-relative: Why do two otherwise comparable cases receive different scores?

These questions can produce different baselines, signs, magnitudes, and rankings. State the intended question before sampling background rows.

Raw lines 5 to 23
24## Background Selection
26Use background data that:
28- comes from the population relevant to the explanation question;
29- passed the same preprocessing and schema validation as explained rows;
30- excludes targets, post-outcome information, identifiers, and leakage fields;
31- includes valid values and missingness patterns;
32- is independent of the specific examples selected for storytelling;
33- is versioned or reproducibly sampled.
35Do not use:
37- the explained row itself as the only background unless a pairwise contrast is explicitly intended;
38- the test target to choose "representative" rows;
39- the full dataset automatically;
40- synthetic mean rows that violate categorical, compositional, or physiological constraints;
41- production rows collected after an outcome if that changes the interpretation.

Background Selection

Use background data that:

  • comes from the population relevant to the explanation question;
  • passed the same preprocessing and schema validation as explained rows;
  • excludes targets, post-outcome information, identifiers, and leakage fields;
  • includes valid values and missingness patterns;
  • is independent of the specific examples selected for storytelling;
  • is versioned or reproducibly sampled.

Do not use:

  • the explained row itself as the only background unless a pairwise contrast is explicitly intended;
  • the test target to choose "representative" rows;
  • the full dataset automatically;
  • synthetic mean rows that violate categorical, compositional, or physiological constraints;
  • production rows collected after an outcome if that changes the interpretation.
Raw lines 24 to 42
43## Size and Convergence
45Larger backgrounds increase cost for interventional tree, deep, kernel, and permutation methods. `Independent` and `Partition` default to at most 100 tabular background rows, including when `TreeExplainer` wraps a bare frame. Increasing `shap.sample(..., 250)` alone therefore does not run a 250-row background experiment. Use `shap.maskers.Independent(background, max_samples=len(background))`, pass that to the explainer, and inspect its effective background before reporting convergence.
47Treat size as an empirical convergence choice:
491. Choose a reproducible candidate pool.
502. Compare baselines and top attribution summaries at increasing sizes, such as 25, 50, 100, and 250.
513. Repeat with multiple seeds when random sampling is used.
524. Stop when conclusions are stable enough for the use case.
535. Record the selected rows or a deterministic selection rule.
55`shap.sample` samples without replacement:
57```python
58background = shap.sample(X_train, 100, random_state=7)
59```
61For heterogeneous populations, stratified sampling may be more appropriate:
63```python
64background = (
65 training_frame.groupby("site", group_keys=False)
66 .sample(n=20, random_state=7)
67 .drop(columns="site")
69```
71Only stratify on information legitimately available at the prediction time and relevant to the reference population.

Size and Convergence

Larger backgrounds increase cost for interventional tree, deep, kernel, and permutation methods. Independent and Partition default to at most 100 tabular background rows, including when TreeExplainer wraps a bare frame. Increasing shap.sample(..., 250) alone therefore does not run a 250-row background experiment. Use shap.maskers.Independent(background, max_samples=len(background)), pass that to the explainer, and inspect its effective background before reporting convergence.

Treat size as an empirical convergence choice:

  1. Choose a reproducible candidate pool.
  2. Compare baselines and top attribution summaries at increasing sizes, such as 25, 50, 100, and 250.
  3. Repeat with multiple seeds when random sampling is used.
  4. Stop when conclusions are stable enough for the use case.
  5. Record the selected rows or a deterministic selection rule.

shap.sample samples without replacement:

background = shap.sample(X_train, 100, random_state=7)

For heterogeneous populations, stratified sampling may be more appropriate:

background = (
    training_frame.groupby("site", group_keys=False)
    .sample(n=20, random_state=7)
    .drop(columns="site")
)

Only stratify on information legitimately available at the prediction time and relevant to the reference population.

Raw lines 43 to 72
73## Tabular Maskers

Tabular Maskers

Raw lines 73 to 74
75### `Independent`
77```python
78masker = shap.maskers.Independent(background, max_samples=100)
79```
81Hidden features are replaced by values from background rows and integrated over that marginal reference distribution.
83Use when:
85- interventional/marginal semantics match the question;
86- the model accepts independently combined columns;
87- a general callable needs a standard tabular masker.
89Risk: combining observed and background columns can create off-manifold or impossible rows when features are dependent.

Independent

masker = shap.maskers.Independent(background, max_samples=100)

Hidden features are replaced by values from background rows and integrated over that marginal reference distribution.

Use when:

  • interventional/marginal semantics match the question;
  • the model accepts independently combined columns;
  • a general callable needs a standard tabular masker.

Risk: combining observed and background columns can create off-manifold or impossible rows when features are dependent.

Raw lines 75 to 90
91### `Partition`
93```python
94masker = shap.maskers.Partition(
95 background,
96 max_samples=100,
97 clustering="correlation",
99```
101`Partition` constrains coalitions using a hierarchical feature tree. With `PartitionExplainer`, this produces Owen values for the constrained game.
103Use when:
105- feature groups should enter together;
106- a hierarchy is scientifically meaningful;
107- correlated or redundant features need grouped interpretation;
108- text tokens or image regions have structure.
110`clustering` can be:
112- a SciPy pairwise-distance metric string; SHAP recommends `"correlation"` for common tabular use;
113- a precomputed linkage matrix encoding a domain-defined hierarchy.
115Correlation clustering is descriptive, not causal. Review the tree rather than assuming automatically derived groups are scientifically valid.

Partition

masker = shap.maskers.Partition(
    background,
    max_samples=100,
    clustering="correlation",
)

Partition constrains coalitions using a hierarchical feature tree. With PartitionExplainer, this produces Owen values for the constrained game.

Use when:

  • feature groups should enter together;
  • a hierarchy is scientifically meaningful;
  • correlated or redundant features need grouped interpretation;
  • text tokens or image regions have structure.

clustering can be:

  • a SciPy pairwise-distance metric string; SHAP recommends "correlation" for common tabular use;
  • a precomputed linkage matrix encoding a domain-defined hierarchy.

Correlation clustering is descriptive, not causal. Review the tree rather than assuming automatically derived groups are scientifically valid.

Raw lines 91 to 116
117### `Impute`
119```python
120masker = shap.maskers.Impute(background, method="linear")
121```
123`Impute` estimates hidden features conditional on observed features. It is commonly paired with `LinearExplainer` for correlation-aware allocations.
125Conditional games can give attribution to a feature the model does not directly use because that feature carries information about a used feature. Do not interpret such an attribution as a model coefficient or intervention effect.

Impute

masker = shap.maskers.Impute(background, method="linear")

Impute estimates hidden features conditional on observed features. It is commonly paired with LinearExplainer for correlation-aware allocations.

Conditional games can give attribution to a feature the model does not directly use because that feature carries information about a used feature. Do not interpret such an attribution as a model coefficient or intervention effect.

Raw lines 117 to 126
127### `Fixed` and composite maskers
129- `Fixed`: leaves an input unchanged; useful for fixed labels or auxiliary arguments.
130- `Composite`: joins maskers for multiple model inputs only when their row counts, call signatures, and clustering are compatible; this is not a universal multimodal adapter.
131- `FixedComposite`: returns both masked and original inputs.
132- `OutputComposite`: combines masking with a model output used by an explanation algorithm.
134Use these only after verifying the model's full call signature with a one-row test.

Fixed and composite maskers

  • Fixed: leaves an input unchanged; useful for fixed labels or auxiliary arguments.
  • Composite: joins maskers for multiple model inputs only when their row counts, call signatures, and clustering are compatible; this is not a universal multimodal adapter.
  • FixedComposite: returns both masked and original inputs.
  • OutputComposite: combines masking with a model output used by an explanation algorithm.

Use these only after verifying the model's full call signature with a one-row test.

Raw lines 127 to 135
136## Domain Maskers

Domain Maskers

Raw lines 136 to 137
138### Text
140```python
141masker = shap.maskers.Text(tokenizer)
142```
144Text masking respects tokenizer boundaries and can create a token hierarchy for `PartitionExplainer`. The mask token, collapse behavior, and tokenizer special tokens affect the explanation.

Text

masker = shap.maskers.Text(tokenizer)

Text masking respects tokenizer boundaries and can create a token hierarchy for PartitionExplainer. The mask token, collapse behavior, and tokenizer special tokens affect the explanation.

Raw lines 138 to 145
146### Image
148```python
149masker = shap.maskers.Image("inpaint_telea", image_shape)
150```
152Supported masking approaches include blurring, inpainting, and constant values. Each asks a different counterfactual question. Inpainting may create plausible local texture but does not guarantee an in-distribution image.
154See [modalities.md](modalities.md) for full workflows.

Image

masker = shap.maskers.Image("inpaint_telea", image_shape)

Supported masking approaches include blurring, inpainting, and constant values. Each asks a different counterfactual question. Inpainting may create plausible local texture but does not guarantee an in-distribution image.

See modalities.md for full workflows.

Raw lines 146 to 155
156## Correlated and Redundant Features
158There is no universally correct single-feature allocation when inputs share information.

Correlated and Redundant Features

There is no universally correct single-feature allocation when inputs share information.

Raw lines 156 to 159
160### Marginal/interventional allocation
162An independent masker asks how model output changes while integrating hidden features over a marginal reference. It can expose the model's functional dependence, including behavior on unrealistic combinations.

Marginal/interventional allocation

An independent masker asks how model output changes while integrating hidden features over a marginal reference. It can expose the model's functional dependence, including behavior on unrealistic combinations.

Raw lines 160 to 163
164### Conditional allocation
166A conditional masker asks how model output changes under an estimated conditional distribution. It may stay closer to the observed manifold if the conditional model is adequate, but can allocate credit to unused correlated features. Linear Gaussian imputation does not guarantee physically valid or categorical states.

Conditional allocation

A conditional masker asks how model output changes under an estimated conditional distribution. It may stay closer to the observed manifold if the conditional model is adequate, but can allocate credit to unused correlated features. Linear Gaussian imputation does not guarantee physically valid or categorical states.

Raw lines 164 to 167
168### Grouped allocation
170A partition game attributes to hierarchical coalitions, reducing arbitrary competition among related features. Individual values remain conditional on the chosen hierarchy.
172For important correlated features:
1741. document correlations and domain relationships;
1752. compare at least two defensible masker/background choices;
1763. report grouped importance where individual allocation is unstable;
1774. avoid causal language;
1785. avoid choosing the masker only because it supports a preferred narrative.

Grouped allocation

A partition game attributes to hierarchical coalitions, reducing arbitrary competition among related features. Individual values remain conditional on the chosen hierarchy.

For important correlated features:

  1. document correlations and domain relationships;
  2. compare at least two defensible masker/background choices;
  3. report grouped importance where individual allocation is unstable;
  4. avoid causal language;
  5. avoid choosing the masker only because it supports a preferred narrative.
Raw lines 168 to 179
180## One-Hot, Encoded, and Engineered Features
182If a model consumes transformed columns, SHAP explains those transformed inputs unless the entire preprocessing pipeline is wrapped in the model callable.

One-Hot, Encoded, and Engineered Features

If a model consumes transformed columns, SHAP explains those transformed inputs unless the entire preprocessing pipeline is wrapped in the model callable.

Raw lines 180 to 183
184### Explain transformed space
186Advantages:
188- specialized model explainers can remain available;
189- additivity is easy to validate;
190- attribution matches the model's actual features.
192Requirements:
194- preserve transformed feature names;
195- group one-hot levels when reporting the source variable;
196- document scaling, imputation, and interactions.
198```python
199feature_names = preprocessor.get_feature_names_out()
200X_background_t = preprocessor.transform(X_background)
201X_eval_t = preprocessor.transform(X_eval)
203explainer = shap.Explainer(
204 model,
205 X_background_t,
206 feature_names=feature_names.tolist(),
208exp = explainer(X_eval_t)
209```
211Only attach names when their order exactly matches the transformed matrix.

Explain transformed space

Advantages:

  • specialized model explainers can remain available;
  • additivity is easy to validate;
  • attribution matches the model's actual features.

Requirements:

  • preserve transformed feature names;
  • group one-hot levels when reporting the source variable;
  • document scaling, imputation, and interactions.
feature_names = preprocessor.get_feature_names_out()
X_background_t = preprocessor.transform(X_background)
X_eval_t = preprocessor.transform(X_eval)

explainer = shap.Explainer(
    model,
    X_background_t,
    feature_names=feature_names.tolist(),
)
exp = explainer(X_eval_t)

Only attach names when their order exactly matches the transformed matrix.

Raw lines 184 to 212
213### Explain raw input space
215Wrap the full pipeline in a callable:
217```python
218def predict_positive(frame):
219 frame = pd.DataFrame(frame, columns=raw_background.columns)
220 return fitted_pipeline.predict_proba(frame)[:, positive_class_index]
222masker = shap.maskers.Independent(raw_background, max_samples=100)
223explainer = shap.PermutationExplainer(
224 predict_positive,
225 masker,
226 feature_names=raw_background.columns.tolist(),
227 seed=7,
229exp = explainer(raw_eval, max_evals=2 * raw_eval.shape[1] + 1)
230```
232This fragment assumes numeric raw columns and a pre-resolved `positive_class_index` from `fitted_pipeline.classes_`. It attributes raw columns but may be much slower. Delta masking can deliver arrays even when the background was a DataFrame, so reconstruct columns inside the callable. Mixed string/object/categorical frames can fail the tabular masker's numeric invariance checks; use a tested domain masker or explain a validated numeric transformed representation. Do not silently convert categories into arbitrary numbers.

Explain raw input space

Wrap the full pipeline in a callable:

def predict_positive(frame):
    frame = pd.DataFrame(frame, columns=raw_background.columns)
    return fitted_pipeline.predict_proba(frame)[:, positive_class_index]

masker = shap.maskers.Independent(raw_background, max_samples=100)
explainer = shap.PermutationExplainer(
    predict_positive,
    masker,
    feature_names=raw_background.columns.tolist(),
    seed=7,
)
exp = explainer(raw_eval, max_evals=2 * raw_eval.shape[1] + 1)

This fragment assumes numeric raw columns and a pre-resolved positive_class_index from fitted_pipeline.classes_. It attributes raw columns but may be much slower. Delta masking can deliver arrays even when the background was a DataFrame, so reconstruct columns inside the callable. Mixed string/object/categorical frames can fail the tabular masker's numeric invariance checks; use a tested domain masker or explain a validated numeric transformed representation. Do not silently convert categories into arbitrary numbers.

Raw lines 213 to 233
234## Missing Values
236Distinguish:
238- naturally missing values the model was trained to handle;
239- values hidden by the SHAP masker;
240- values imputed by preprocessing.
242Do not manually replace masked values with `NaN` unless the masker and model are designed for that operation. For tree models, missing-value routing can be model-library-specific. Validate explanations after upgrading SHAP or the tree library.

Missing Values

Distinguish:

  • naturally missing values the model was trained to handle;
  • values hidden by the SHAP masker;
  • values imputed by preprocessing.

Do not manually replace masked values with NaN unless the masker and model are designed for that operation. For tree models, missing-value routing can be model-library-specific. Validate explanations after upgrading SHAP or the tree library.

Raw lines 234 to 243
244## Backgrounds for Cohort Comparisons
246Use a shared background when comparing cohorts if the goal is to compare model behavior against one common reference. Separate cohort-specific backgrounds change both baselines and attributions, confounding reference-population differences with model-use differences.
248If separate backgrounds are scientifically necessary:
250- present each baseline;
251- avoid direct magnitude comparisons without qualification;
252- run a shared-background sensitivity analysis.

Backgrounds for Cohort Comparisons

Use a shared background when comparing cohorts if the goal is to compare model behavior against one common reference. Separate cohort-specific backgrounds change both baselines and attributions, confounding reference-population differences with model-use differences.

If separate backgrounds are scientifically necessary:

  • present each baseline;
  • avoid direct magnitude comparisons without qualification;
  • run a shared-background sensitivity analysis.
Raw lines 244 to 253
254## Fairness and Protected Attributes
256A background distribution can change subgroup explanations but cannot establish fairness.
258Do not infer:
260- "the model is fair" because a protected feature has low mean absolute SHAP;
261- "the model does not use race/sex/age" because the explicit column is absent;
262- "removing the feature fixed bias";
263- "equal mean SHAP implies equal treatment."
265Proxy features, calibration, base rates, thresholds, error rates, and label quality require separate analysis.

Fairness and Protected Attributes

A background distribution can change subgroup explanations but cannot establish fairness.

Do not infer:

  • "the model is fair" because a protected feature has low mean absolute SHAP;
  • "the model does not use race/sex/age" because the explicit column is absent;
  • "removing the feature fixed bias";
  • "equal mean SHAP implies equal treatment."

Proxy features, calibration, base rates, thresholds, error rates, and label quality require separate analysis.

Raw lines 254 to 266
267## Reproducibility Record
269Store:
271- a hash or immutable identifier for background rows;
272- sampling code and seed;
273- raw and transformed feature schemas;
274- masker class and parameters;
275- output method, index, names, and units;
276- model and preprocessing versions;
277- SHAP and dependency versions;
278- explanation row identifiers in a separate, access-controlled artifact if identifiers are sensitive.
280Do not place secrets, protected health information, or direct identifiers into plot labels or exported explanation JSON.

Reproducibility Record

Store:

  • a hash or immutable identifier for background rows;
  • sampling code and seed;
  • raw and transformed feature schemas;
  • masker class and parameters;
  • output method, index, names, and units;
  • model and preprocessing versions;
  • SHAP and dependency versions;
  • explanation row identifiers in a separate, access-controlled artifact if identifiers are sensitive.

Do not place secrets, protected health information, or direct identifiers into plot labels or exported explanation JSON.

Raw lines 267 to 281
282## Sources
284- Masker API: https://shap.readthedocs.io/en/latest/api.html#maskers
285- Independent masker: https://shap.readthedocs.io/en/latest/generated/shap.maskers.Independent.html
286- Partition masker: https://shap.readthedocs.io/en/latest/generated/shap.maskers.Partition.html
287- Impute masker: https://shap.readthedocs.io/en/latest/generated/shap.maskers.Impute.html
288- Causal interpretation caution: https://shap.readthedocs.io/en/latest/example_notebooks/overviews/Be%20careful%20when%20interpreting%20predictive%20models%20in%20search%20of%20causal%20insights.html

Sources

  • Masker API: https://shap.readthedocs.io/en/latest/api.html#maskers
  • Independent masker: https://shap.readthedocs.io/en/latest/generated/shap.maskers.Independent.html
  • Partition masker: https://shap.readthedocs.io/en/latest/generated/shap.maskers.Partition.html
  • Impute masker: https://shap.readthedocs.io/en/latest/generated/shap.maskers.Impute.html
  • Causal interpretation caution: https://shap.readthedocs.io/en/latest/example_notebooks/overviews/Be%20careful%20when%20interpreting%20predictive%20models%20in%20search%20of%20causal%20insights.html
Raw lines 282 to 288