Approximates SHAP values using block-conditional expectations instead of naive row permutation. Standard SHAP marginalizes over all observations, which creates impossible feature combinations when data is spatially structured. Spatial SHAP marginalizes within spatial blocks, preserving realistic covariate relationships.
Usage
borg_shap(
model,
data,
target,
coords = NULL,
predictors = NULL,
n_blocks = 10,
n_samples = 50,
explain_idx = NULL,
seed = 42
)Arguments
- model
A fitted model with a
predict()method.- data
Data frame with predictors.
- target
Character. Target variable name (excluded from SHAP).
- coords
Character vector of length 2. Coordinate column names. If provided, uses spatial blocking for marginal expectations.
- predictors
Character vector. Variables to compute SHAP for. If
NULL, uses all numeric columns except target and coords.- n_blocks
Integer. Number of spatial blocks for marginal expectations. Default: 10.
- n_samples
Integer. Number of background samples per block for marginal expectations. Default: 50.
- explain_idx
Integer vector. Row indices to explain. If
NULL, explains all rows (can be slow).- seed
Integer. Random seed. Default: 42.
Value
A list with class "borg_shap" containing:
- shap_values
Matrix (n_explain x n_predictors) of SHAP values
- baseline
Mean prediction (expected value)
- feature_importance
Named vector of mean |SHAP| per feature
- predictors
Feature names
- method
"spatial_block" or "standard"
Has print() and autoplot() methods.
Details
Algorithm
For each observation \(x_i\) and feature \(j\):
Identify the spatial block containing \(x_i\).
Sample background points from other blocks.
Compute marginal contribution: replace feature \(j\) with values from background points, keeping all other features fixed.
Average the change in prediction.
This approximates the Shapley value while respecting spatial structure.