shap: Compute SHAP values for a prediction rule ensemble

View source: R/shap.R

shapR Documentation

Compute SHAP values for a prediction rule ensemble

Description

This function computes the marginal (interaction) SHAP values for a prediction rule ensemble as fitted with function pre.

Usage

shap(
  object,
  newdata = NULL,
  reference_data = NULL,
  penalty.par.val = "lambda.1se",
  interactions = FALSE,
  block_size = 5000,
  ...
)

Arguments

object

object of class pre

newdata

An optional data.frame containing observations for which SHAP values should be computed. If NULL, SHAP values will be computed for the model's training data, obtained from object.

reference_data

An optional data.frame containing the reference data used to estimate the expectations in the SHAP values. If NULL, the model's training data will be used, obtained from object.

penalty.par.val

character or numeric. Value of the penalty parameter \lambda to be employed for selecting the final ensemble. The default "lambda.1se" employs the \lambda value within 1 standard error of the minimum cross-validated error. Alternatively, "lambda.min" may be specified, to employ the \lambda value with minimum cross-validated error, or a numeric value >0 may be specified, with higher values yielding a sparser ensemble. To evaluate the trade-off between accuracy and sparsity of the final ensemble, inspect pre_object$glmnet.fit and plot(pre_object$glmnet.fit).

interactions

A logical value indicating whether marginal interaction SHAP values should be computed, on top of the overall values.

block_size

Computation of SHAP values involves computations on large matrices. For computational reasons, these are split into small submatrices. This integer denotes the number of rows of the submatrix.

...

Further arguments to be passed to coef.cv.glmnet.

Details

Adapted code from original written by and used with permission from Giorgio Spadaccini.

Value

A list with two objects:

marginal An $N$ by $p$ matrix with SHAP values for each observation (rows) and predictor (columns), with rownames corresponding to rownames(newdata).

interactions A $p$ by $p$ by $N$ array with SHAP interaction values. Each slice contains a $p /times p$ symmetric matrix, of which the diagonal entries present the predictor variables' main effect SHAP values and the off-diagonal entries represent their interaction SHAP values.

All SHAP values are on the scale of the linear predictor.

Author(s)

Giorgio Spadaccini

#' @seealso print.pre, plot.pre, coef.pre, importance.pre, predict.pre, interact, cvpre

Examples

## Fit pre, then compute SHAP values for the first 10 training observations 
airq <- airquality[complete.cases(airquality), ]
set.seed(42) 
airq.ens <- pre(Ozone ~ ., data = airq)
airq.shap <- shap(airq.ens, newdata = airq[1:10, ])


pre documentation built on Sept. 1, 2026, 1:06 a.m.