### Multi-output Models Example Setup Source: https://modeloriented.r-universe.dev/kernelshap Initializes libraries and sets seed for demonstrating support for multi-output models with kernelshap, using the iris dataset. ```r library(kernelshap) library(ranger) library(shapviz) set.seed(1) ``` -------------------------------- ### Install kernelshap development version Source: https://modeloriented.r-universe.dev/kernelshap Installs the development version of the kernelshap package directly from its GitHub repository. ```r # Or the development version: # install.packages("remotes") # remotes::install_github("modeloriented/kernelshap") ``` -------------------------------- ### Install kernelshap Package Source: https://modeloriented.r-universe.dev/kernelshap Installs the kernelshap package from a specific R-universe repository or CRAN. ```r install.packages("kernelshap", repos = c('https://modeloriented.r-universe.dev', 'https://cloud.r-project.org')) ``` -------------------------------- ### Print KernelSHAP object Source: https://modeloriented.r-universe.dev/kernelshap/doc/manual.html This example demonstrates how to print a 'kernelshap' object. The print method allows controlling the number of rows displayed. ```R fit <- lm(Sepal.Length ~ ., data = iris) s <- kernelshap(fit, iris[1:3, -1], bg_X = iris[, -1]) s ``` -------------------------------- ### Install kernelshap from CRAN Source: https://modeloriented.r-universe.dev/kernelshap Installs the kernelshap package from the CRAN repository, including the modeloriented R-universe repository. ```r install.packages('kernelshap', repos = c('https://modeloriented.r-universe.dev', 'https://cloud.r-project.org')) ``` -------------------------------- ### Calculate SHAP values for a multi-response linear regression model Source: https://modeloriented.r-universe.dev/kernelshap/doc/manual.html This example shows how to compute SHAP values for a multi-response linear regression model. It highlights the flexibility of permshap in handling models with multiple output variables. ```R fit <- lm(as.matrix(iris[, 1:2]) ~ Petal.Length + Petal.Width + Species, data = iris) s <- permshap(fit, iris[3:5]) s ``` -------------------------------- ### KernelSHAP with Logistic Regression (Logit Scale) Source: https://modeloriented.r-universe.dev/kernelshap/NEWS.txt Example of using kernelshap for logistic regression on the logit scale. Requires a fitted model object and background data. ```R kernelshap(fit, X, bg_X) ``` -------------------------------- ### KernelSHAP with Logistic Regression (Probabilities) Source: https://modeloriented.r-universe.dev/kernelshap/NEWS.txt Example of using kernelshap for logistic regression to predict probabilities. Specify 'response' for the type argument. ```R kernelshap(fit, X, bg_X, type = "response") ``` -------------------------------- ### KernelSHAP with Custom Prediction Function (Linear Regression) Source: https://modeloriented.r-universe.dev/kernelshap/NEWS.txt Example demonstrating how to use a custom prediction function with kernelshap for linear regression with a logarithmic response, evaluated on the original scale. The custom function `pred_fun` is defined to use `exp(predict(m, X))`. ```R kernelshap(fit, X, bg_X, pred_fun = function(m, X) exp(predict(m, X))) ``` -------------------------------- ### Parallel Computing with GAM Model Source: https://modeloriented.r-universe.dev/kernelshap Demonstrates using parallel computing for permshap with a Generalized Additive Model (GAM) using the mgcv package. Requires setting up a parallel plan with doFuture and foreach. ```r library(doFuture) library(mgcv) plan(multisession, workers = 4) # Windows # plan(multicore, workers = 4) # Linux, macOS, Solaris # GAM with interactions - we cannot use additive_shap() fit <- gam(log_price ~ s(log_carat) + clarity * color + cut, data = diamonds) system.time( # 4 seconds in parallel ps <- permshap( fit, X, bg_X = bg_X, parallel = TRUE, parallel_args = list(packages = "mgcv") ) ) ps # SHAP values of first observations: # log_carat clarity color cut # [1,] 1.26801 0.1023518 -0.09223291 0.004512402 # [2,] -0.51546 -0.1174766 0.11122775 0.030243973 # Because there are no interactions of order above 2, Kernel SHAP gives the same: system.time( # 12 s non-parallel ks <- kernelshap(fit, X, bg_X = bg_X) ) all.equal(ps$S, ks$S) # [1] TRUE # Now the usual plots: sv <- shapviz(ps) sv_importance(sv, kind = "bee") sv_dependence(sv, xvars) ``` -------------------------------- ### Additive SHAP Explanation Source: https://modeloriented.r-universe.dev/kernelshap Demonstrates using the additive explainer for linear models to extract feature contributions. Results are then visualized using shapviz. ```r fit <- lm(log(price) ~ log(carat) + color + clarity + cut, data = diamonds) shap_values <- additive_shap(fit, diamonds) |> shapviz() sv_importance(shap_values) sv_dependence(shap_values, v = "carat", color_var = NULL) ``` -------------------------------- ### Calculate SHAP values with specified feature names and background data Source: https://modeloriented.r-universe.dev/kernelshap/doc/manual.html This snippet illustrates how to use the 'feature_names' argument and provide background data ('bg_X') when calculating SHAP values. This is particularly useful when the input data 'X' is small. ```R s <- permshap( fit, iris[1:4, ], bg_X = iris, feature_names = c("Petal.Length", "Petal.Width", "Species") ) s ``` -------------------------------- ### Basic Usage: Random Forest Model Source: https://modeloriented.r-universe.dev/kernelshap Demonstrates fitting a random forest model to predict diamond prices and calculating SHAP values using permshap and kernelshap. Requires loading several libraries and preparing data. ```r library(kernelshap) library(ggplot2) library(ranger) library(shapviz) options(ranger.num.threads = 8) diamonds <- transform( diamonds, log_price = log(price), log_carat = log(carat) ) xvars <- c("log_carat", "clarity", "color", "cut") fit <- ranger( log_price ~ log_carat + log_carat + clarity + color + cut, data = diamonds, num.trees = 100, seed = 20 ) fit # OOB R-squared 0.989 # 1) Sample rows to be explained set.seed(10) X <- diamonds[sample(nrow(diamonds), 1000), xvars] # 2) Optional: Select background data. If unspecified, 200 rows from X are used bg_X <- diamonds[sample(nrow(diamonds), 200), ] # 3) Crunch SHAP values (22 seconds) # Since the number of features is small, we use permshap() system.time( ps <- permshap(fit, X, bg_X = bg_X) ) ps # SHAP values of first observations: log_carat clarity color cut [1,] 1.1913247 0.09005467 -0.13430720 0.000682593 [2,] -0.4931989 -0.11724773 0.09868921 0.028563613 # Indeed, Kernel SHAP gives the same: ks <- kernelshap(fit, X, bg_X = bg_X) ks log_carat clarity color cut [1,] 1.1913247 0.09005467 -0.13430720 0.000682593 [2,] -0.4931989 -0.11724773 0.09868921 0.028563613 # 4) Analyze with {shapviz} ps <- shapviz(ps) sv_importance(ps) sv_dependence(ps, xvars) ``` -------------------------------- ### KernelSHAP with Tidymodels for Classification Source: https://modeloriented.r-universe.dev/kernelshap Demonstrates using KernelSHAP with a tidymodels workflow for classification. The `...` arguments are passed to `predict()`. ```R library(kernelshap) library(tidymodels) set.seed(1) iris_recipe <- iris |> recipe(Species ~ .) mod <- rand_forest(trees = 100) |> set_engine("ranger") |> set_mode("classification") iris_wf <- workflow() |> add_recipe(iris_recipe) |> add_model(mod) fit <- iris_wf |> fit(iris) system.time( # 3s ps <- permshap(fit, iris[-5], type = "prob") ) ps # Some values $.pred_setosa Sepal.Length Sepal.Width Petal.Length Petal.Width [1,] 0.02186111 0.012137778 0.3658278 0.2667667 [2,] 0.02628333 0.001315556 0.3683833 0.2706111 ``` -------------------------------- ### Summarize KernelSHAP object Source: https://modeloriented.r-universe.dev/kernelshap/doc/manual.html This snippet shows how to summarize a 'kernelshap' object. The summary method provides a concise overview of the SHAP values and related information, with an option for a compact view. ```R fit <- lm(Sepal.Length ~ ., data = iris) s <- kernelshap(fit, iris[1:3, -1], bg_X = iris[, -1]) summary(s) ``` -------------------------------- ### Citation for kernelshap package Source: https://modeloriented.r-universe.dev/kernelshap Provides the recommended citation for the kernelshap R package in publications, including author, year, title, and URL. ```bibtex @Manual{, title = {kernelshap: Kernel SHAP}, author = {Michael Mayer and David Watson}, year = {2025}, note = {R package version 0.9.1}, url = {https://github.com/modeloriented/kernelshap}, } ``` -------------------------------- ### PermutationSHAP Default Method Usage Source: https://modeloriented.r-universe.dev/kernelshap/doc/manual.html Demonstrates the default S3 method for the permshap function. This is used for calculating Permutation SHAP values for a given model object and data. ```R permshap( object, X, bg_X = NULL, pred_fun = stats::predict, feature_names = colnames(X), bg_w = NULL, bg_n = 200L, exact = length(feature_names) <= 8L, low_memory = length(feature_names) > 15L, tol = 0.01, max_iter = 10L * length(feature_names), parallel = FALSE, parallel_args = NULL, verbose = TRUE, seed = NULL, ... ) ``` -------------------------------- ### kernelshap Source: https://modeloriented.r-universe.dev/kernelshap/doc/manual.html Efficient implementation of Kernel SHAP. It calculates SHAP values, using exact methods for up to 8 features and a hybrid algorithm for more features. Supports various models and provides options for background data and parallel computation. ```APIDOC ## Kernel SHAP ### Description Efficient implementation of Kernel SHAP, see Lundberg and Lee (2017), and Covert and Lee (2021), abbreviated by CL21. By default, for up to p=8 features, exact SHAP values are returned (with respect to the selected background data). Otherwise, a partly exact hybrid algorithm combining exact calculations and iterative paired sampling is used, see Details. ### Usage ```R kernelshap(object, ...) ``` ### Arguments `object` | A fitted model object. `...` | Further arguments passed to specific methods. See `kernelshap.lm`, `kernelshap.glm`, etc. ### Details For models with more than 8 features, the algorithm uses iterative paired sampling to approximate SHAP values. The number of iterations can be controlled via the `n_iter` argument. The background data `bg_X` is crucial for the SHAP value calculation and should ideally represent the data distribution. ### Value An object of class "kernelshap" with components: * `S`: A matrix of SHAP values. * `X`: The input data `X`. * `bg_X`: The background data used. * `baseline`: The baseline prediction. * `algorithm`: The algorithm used ('kernel_shap' or 'hybrid_kernel_shap'). * `n_iter`: Number of iterations if the hybrid algorithm was used. * `predictions`: Predictions on the background data. ### Examples ```R # Example with a linear model fit <- lm(Sepal.Length ~ ., data = iris) shap_values <- kernelshap(fit, iris[, -1], bg_X = iris[, -1]) print(shap_values) # Example with a more complex model (e.g., randomForest) # library(randomForest) # rf_model <- randomForest(Species ~ ., data = iris) # shap_rf <- kernelshap(rf_model, iris[, -1], bg_X = iris[, -1]) # print(shap_rf) ``` ``` -------------------------------- ### BibTeX Entry for LaTeX Source: https://modeloriented.r-universe.dev/kernelshap/citation This BibTeX entry can be used in LaTeX documents to cite the kernelshap R package. ```bibtex @Manual{ title = {kernelshap: Kernel SHAP}, author = {Michael Mayer and David Watson}, year = {2025}, note = {R package version 0.9.1}, url = {https://github.com/modeloriented/kernelshap}, } ``` -------------------------------- ### PermutationSHAP Ranger Method Usage Source: https://modeloriented.r-universe.dev/kernelshap/doc/manual.html Shows the S3 method for the permshap function specifically for 'ranger' objects. This allows calculating Permutation SHAP values for models trained with the ranger package. ```R permshap( object, X, bg_X = NULL, pred_fun = NULL, feature_names = colnames(X), bg_w = NULL, bg_n = 200L, exact = length(feature_names) <= 8L, low_memory = length(feature_names) > 15L, tol = 0.01, max_iter = 10L * length(feature_names), parallel = FALSE, parallel_args = NULL, verbose = TRUE, seed = NULL, survival = c("chf", "prob"), ... ) ``` -------------------------------- ### KernelSHAP with Caret for Regression Source: https://modeloriented.r-universe.dev/kernelshap Shows how to use KernelSHAP with a caret-trained linear model. The `permshap` function is called with the fitted model and the data. ```R library(kernelshap) library(caret) fit <- train( Sepal.Length ~ ., data = iris, method = "lm", tuneGrid = data.frame(intercept = TRUE), trControl = trainControl(method = "none") ) ps <- permshap(fit, iris[-1]) ``` -------------------------------- ### KernelSHAP S3 Method for 'ranger' Class Source: https://modeloriented.r-universe.dev/kernelshap/doc/manual.html This S3 method is specifically for objects of class 'ranger'. It includes an additional 'survival' parameter to handle survival analysis models, allowing calculation of SHAP values for 'chf' (cumulative hazard function) or 'prob' (survival probability). ```R kernelshap( object, X, bg_X = NULL, pred_fun = NULL, feature_names = colnames(X), bg_w = NULL, bg_n = 200L, exact = length(feature_names) <= 8L, hybrid_degree = 1L + length(feature_names) %in% 4:16, m = 2L * length(feature_names) * (1L + 3L * (hybrid_degree == 0L)), tol = 0.005, max_iter = 100L, parallel = FALSE, parallel_args = NULL, verbose = TRUE, seed = NULL, survival = c("chf", "prob"), ... ) ``` -------------------------------- ### kernelshap S3 Method for 'ranger' Class Source: https://modeloriented.r-universe.dev/kernelshap/doc/manual.html A specialized S3 method for the `kernelshap` function when the model object is of class 'ranger'. It includes an additional `survival` parameter for survival models. ```APIDOC ## kernelshap(object, X, ...) ### Description This S3 method is specifically for `ranger` model objects. It computes SHAP values for ranger models, with an option to specify the survival outcome type. ### Parameters - **object**: The ranger model object. - **X**: The data frame or matrix of features. - **bg_X**: Background data for KernelSHAP. Defaults to NULL. - **pred_fun**: A function to predict from the model object. Defaults to NULL (will use ranger's predict method). - **feature_names**: A character vector of feature names to consider. Defaults to column names of X. - **bg_w**: Weights for the background data. Defaults to NULL. - **bg_n**: Number of background samples to use. Defaults to 200. - **exact**: Logical, whether to use exact computation. Defaults to TRUE if number of features <= 8. - **hybrid_degree**: Degree for hybrid approximation. Defaults to 1 + number of features in [4, 16]. - **m**: Parameter related to the number of background samples and hybrid degree. Defaults to 2 * number of features * (1 + 3 * (hybrid_degree == 0)). - **tol**: Tolerance for convergence. Defaults to 0.005. - **max_iter**: Maximum number of iterations. Defaults to 100. - **parallel**: Logical, whether to use parallel processing. Defaults to FALSE. - **parallel_args**: Arguments for parallel processing. Defaults to NULL. - **verbose**: Logical, whether to print verbose output. Defaults to TRUE. - **seed**: Random seed for reproducibility. Defaults to NULL. - **survival**: Type of survival outcome to compute SHAP values for. Can be 'chf' (cumulative hazard function) or 'prob' (survival probability). Defaults to c("chf", "prob"). - **...**: Additional arguments. ``` -------------------------------- ### KernelSHAP Default S3 Method Source: https://modeloriented.r-universe.dev/kernelshap/doc/manual.html This is the default S3 method for the kernelshap function. It is used when no specific method for the object class is found. It defines parameters for calculating SHAP values for a given model and data. ```R kernelshap( object, X, bg_X = NULL, pred_fun = stats::predict, feature_names = colnames(X), bg_w = NULL, bg_n = 200L, exact = length(feature_names) <= 8L, hybrid_degree = 1L + length(feature_names) %in% 4:16, m = 2L * length(feature_names) * (1L + 3L * (hybrid_degree == 0L)), tol = 0.005, max_iter = 100L, parallel = FALSE, parallel_args = NULL, verbose = TRUE, seed = NULL, ... ) ``` -------------------------------- ### KernelSHAP with Linear Regression (Iris Dataset) Source: https://modeloriented.r-universe.dev/kernelshap/doc/manual.html Calculates SHAP values for a linear regression model using the Iris dataset. Ensure sufficient background data (bg_X) is provided, especially when the explanation dataset (X) is small. ```R s <- kernelshap( fit, iris[1:4, ], bg_X = iris, feature_names = c("Petal.Length", "Petal.Width", "Species") ) s ``` ```R fit <- lm(Sepal.Length ~ ., data = iris) X_explain <- iris[-1] s <- kernelshap(fit, X_explain) s ``` -------------------------------- ### kernelshap Default S3 Method Source: https://modeloriented.r-universe.dev/kernelshap/doc/manual.html The default S3 method for the kernelshap function, used for general model objects. It allows customization of background data, prediction functions, feature names, and various computational parameters. ```APIDOC ## kernelshap(object, X, ...) ### Description This is the default S3 method for the `kernelshap` function. It computes SHAP values for a given model `object` and data `X` using the KernelSHAP algorithm. ### Parameters - **object**: The model object for which to compute SHAP values. - **X**: The data frame or matrix of features for which to compute SHAP values. - **bg_X**: Background data for KernelSHAP. Defaults to NULL. - **pred_fun**: A function to predict from the model object. Defaults to `stats::predict`. - **feature_names**: A character vector of feature names to consider. Defaults to column names of X. - **bg_w**: Weights for the background data. Defaults to NULL. - **bg_n**: Number of background samples to use. Defaults to 200. - **exact**: Logical, whether to use exact computation. Defaults to TRUE if number of features <= 8. - **hybrid_degree**: Degree for hybrid approximation. Defaults to 1 + number of features in [4, 16]. - **m**: Parameter related to the number of background samples and hybrid degree. Defaults to 2 * number of features * (1 + 3 * (hybrid_degree == 0)). - **tol**: Tolerance for convergence. Defaults to 0.005. - **max_iter**: Maximum number of iterations. Defaults to 100. - **parallel**: Logical, whether to use parallel processing. Defaults to FALSE. - **parallel_args**: Arguments for parallel processing. Defaults to NULL. - **verbose**: Logical, whether to print verbose output. Defaults to TRUE. - **seed**: Random seed for reproducibility. Defaults to NULL. - **...**: Additional arguments. ``` -------------------------------- ### Calculate SHAP values for a linear regression model Source: https://modeloriented.r-universe.dev/kernelshap/doc/manual.html This snippet demonstrates how to calculate SHAP values for a linear regression model using the permshap function. It involves fitting a linear model, selecting feature columns for explanation, and then computing the SHAP values. ```R fit <- lm(Sepal.Length ~ ., data = iris) # Select rows to explain (only feature columns) X_explain <- iris[-1] # Calculate SHAP values s <- permshap(fit, X_explain) s ``` -------------------------------- ### Fit Ranger for Probabilistic Classification Source: https://modeloriented.r-universe.dev/kernelshap Fit a ranger model for classification with probability output. This is a prerequisite for using KernelSHAP with probabilistic predictions. ```R fit_prob <- ranger(Species ~ ., data = iris, probability = TRUE) ps_prob <- permshap(fit_prob, X = iris[-5]) | shapviz() sv_importance(ps_prob) sv_dependence(ps_prob, "Petal.Length") ``` -------------------------------- ### Calculate Additive SHAP for Linear Models Source: https://modeloriented.r-universe.dev/kernelshap/doc/manual.html Calculates exact additive SHAP values for models fitted with lm(), glm(), gam(), coxph(), and survreg(). Models with interactions or complex terms are not supported. Ensure background data matches training data for comparison with kernelshap()/permshap(). ```R fit <- lm(Sepal.Length ~ ., data = iris) s <- additive_shap(fit, head(iris)) s ``` ```R fit <- lm( Sepal.Length ~ poly(Sepal.Width, 2) + log(Petal.Length) + log(Sepal.Width), data = iris ) s_add <- additive_shap(fit, head(iris)) s_add ``` ```R s_kernel <- kernelshap( fit, head(iris[c("Sepal.Width", "Petal.Length")]), bg_X = iris ) all.equal(s_add$S, s_kernel$S) ``` -------------------------------- ### R Package Citation Source: https://modeloriented.r-universe.dev/kernelshap/citation Use this format when citing the kernelshap R package in R-related publications or documentation. ```r > Mayer M, Watson D (2025). _kernelshap: Kernel SHAP_. R package version 0.9.1, https://github.com/modeloriented/kernelshap. ``` -------------------------------- ### additive_shap Source: https://modeloriented.r-universe.dev/kernelshap/doc/manual.html Calculates exact additive SHAP values assuming feature independence for supported additive models like lm(), glm(), gam(), coxph(), and survreg(). It extracts SHAP values via predict(object, newdata = X, type = "terms"). ```APIDOC ## additive_shap ### Description Exact additive SHAP assuming feature independence. The implementation works for models fitted via * `lm()`, * `glm()`, * `mgcv::gam()`, * `mgcv::bam()`, * `gam::gam()`, * `survival::coxph()`, * `survival::survreg()`. ### Usage ```R additive_shap(object, X, verbose = TRUE, ...) ``` ### Arguments `object` | Fitted additive model. `X` | Dataframe with rows to be explained. Passed to `predict(object, newdata = X, type = "terms")`. `verbose` | Set to `FALSE` to suppress messages. `...` | Currently unused. ### Details The SHAP values are extracted via `predict(object, newdata = X, type = "terms")`, a logic adopted from `fastshap:::explain.lm(..., exact = TRUE)`. Models with interactions (specified via `:` or `*`), or with terms of multiple features like `log(x1/x2)` are not supported. Note that the SHAP values obtained by `additive_shap()` are expected to match those of `permshap()` and `kernelshap()` as long as their background data equals the full training data (which is typically not feasible). ### Value An object of class "kernelshap" with the following components: * `S`: `(n×p)(n \times p)(n×p)` matrix with SHAP values. * `X`: Same as input argument `X`. * `baseline`: The baseline. * `exact`: `TRUE`. * `txt`: Summary text. * `predictions`: Vector with predictions of `X` on the scale of "terms". * `algorithm`: "additive_shap". ### Examples ```R # MODEL ONE: Linear regression fit <- lm(Sepal.Length ~ ., data = iris) s <- additive_shap(fit, head(iris)) s # MODEL TWO: More complicated (but not very clever) formula fit <- lm( Sepal.Length ~ poly(Sepal.Width, 2) + log(Petal.Length) + log(Sepal.Width), data = iris ) s_add <- additive_shap(fit, head(iris)) s_add # Equals kernelshap()/permshap() when background data is full training data s_kernel <- kernelshap( fit, head(iris[c("Sepal.Width", "Petal.Length")]), bg_X = iris ) all.equal(s_add$S, s_kernel$S) ``` ``` -------------------------------- ### Calculate SHAP values for Multi-response Linear Regression Source: https://modeloriented.r-universe.dev/kernelshap/doc/manual.html Calculates SHAP values for a multi-response linear regression model. The model output and input data should correspond to the multiple responses. ```R fit <- lm(as.matrix(iris[, 1:2]) ~ Petal.Length + Petal.Width + Species, data = iris) s <- kernelshap(fit, iris[3:5]) s ``` -------------------------------- ### Custom Predict Function for Keras Model Source: https://modeloriented.r-universe.dev/kernelshap Shows how to use a custom prediction function with permshap for a Keras neural network model. The custom function ensures compatibility with Keras API, uses large batches, and disables the progress bar. ```r library(keras) nn <- keras_model_sequential() nn |> layer_dense(units = 30, activation = "relu", input_shape = 4) |> layer_dense(units = 15, activation = "relu") |> layer_dense(units = 1) nn |> compile(optimizer = optimizer_adam(0.001), loss = "mse") cb <- list( callback_early_stopping(patience = 20), callback_reduce_lr_on_plateau(patience = 5) ) nn |> fit( x = data.matrix(diamonds[xvars]), y = diamonds$log_price, epochs = 100, batch_size = 400, validation_split = 0.2, callbacks = cb ) pred_fun <- function(mod, X) predict(mod, data.matrix(X), batch_size = 1e4, verbose = FALSE, workers = 4) system.time( # 42 s ps <- permshap(nn, X, bg_X = bg_X, pred_fun = pred_fun) ) ps <- shapviz(ps) sv_importance(ps, show_numbers = TRUE) sv_dependence(ps, xvars) ``` -------------------------------- ### KernelSHAP Generic Function Call Source: https://modeloriented.r-universe.dev/kernelshap/doc/manual.html This represents a generic call to the kernelshap function, typically used for dispatching to the appropriate S3 method based on the class of the 'object' argument. It accepts additional arguments via '...'. ```R kernelshap(object, ...) ``` -------------------------------- ### KernelSHAP with mlr3 for Classification Source: https://modeloriented.r-universe.dev/kernelshap Integrates KernelSHAP with mlr3 for classification tasks. Ensures `predict_type = "prob"` is set for the learner and passed to `permshap`. ```R library(kernelshap) library(mlr3) library(mlr3learners) set.seed(1) task_classif <- TaskClassif$new(id = "1", backend = iris, target = "Species") learner_classif <- lrn("classif.rpart", predict_type = "prob") learner_classif$train(task_classif) x <- learner_classif$selected_features() # Don't forget to pass predict_type = "prob" to mlr3's predict() ps <- permshap( learner_classif, X = iris, feature_names = x, predict_type = "prob" ) ps # $setosa # Petal.Length Petal.Width # [1,] 0.6666667 0 # [2,] 0.6666667 0 ``` -------------------------------- ### Calculate SHAP values for Linear Regression Source: https://modeloriented.r-universe.dev/kernelshap/doc/manual.html Calculates SHAP values for a linear regression model using the kernelshap function. Ensure the model and data are correctly prepared. ```R fit <- lm(Sepal.Length ~ ., data = iris) # Select rows to explain (only feature columns) X_explain <- iris[-1] # Calculate SHAP values s <- kernelshap(fit, X_explain) s ``` -------------------------------- ### Check if an Object is of Class 'kernelshap' Source: https://modeloriented.r-universe.dev/kernelshap/doc/manual.html Verifies if a given R object is of the class 'kernelshap'. This is useful for confirming the output type of kernelshap functions. ```R fit <- lm(Sepal.Length ~ ., data = iris) s <- kernelshap(fit, iris[1:2, -1], bg_X = iris[, -1]) is.kernelshap(s) is.kernelshap("a") ``` -------------------------------- ### is.kernelshap Source: https://modeloriented.r-universe.dev/kernelshap/doc/manual.html Checks if an object is of class "kernelshap". This is a utility function to verify the type of the returned object from kernelshap functions. ```APIDOC ## is.kernelshap ### Description Is object of class "kernelshap"? ### Usage ```R is.kernelshap(object) ``` ### Arguments `object` | An R object. ### Value `TRUE` if `object` is of class "kernelshap", and `FALSE` otherwise. ### See Also `kernelshap()` ### Examples ```R fit <- lm(Sepal.Length ~ ., data = iris) s <- kernelshap(fit, iris[1:2, -1], bg_X = iris[, -1]) is.kernelshap(s) is.kernelshap("a") ``` ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.