This implements SHAP-like explanations using finite differences to approximate gradients for any function f, extending the linear SHAP concept to nonlinear models. Compute gradient-based SHAP values for any function

gradient_shap(
  f,
  X_train,
  X_new,
  h = 1e-05,
  baseline_method = "mean",
  scale_by_range = FALSE
)

Arguments

f

Function to explain (should accept matrix input, return vector output)

X_train

Training data (for computing baseline and feature means)

X_new

New observations to explain

h

Step size for finite differences (default: 1e-5)

baseline_method

Method for computing baseline: "mean", "median", "zero", or custom vector

scale_by_range

Whether to scale gradients by feature ranges

Value

List with gradient-SHAP values, baseline, and predictions