### XGBoost analysis example (basic) Source: https://github.com/modeloriented/shapviz/blob/main/_autodocs/_SUMMARY.txt A basic workflow example demonstrating SHAP visualization for an XGBoost model. ```R library(shapviz) library(xgboost) # Train a simple XGBoost model (example data) data(iris) # Prepare data for XGBoost features <- setdiff(names(iris), "Species") X_train <- as.matrix(iris[, features]) y_train <- as.numeric(iris$Species) - 1 # Binary classification example xgb_model <- xgboost(data = X_train, label = y_train, nrounds = 10) # Create shapviz object sv_object <- shapviz(xgb_model, X_train = X_train) # Plot feature importance sv_importance(sv_object) ``` -------------------------------- ### Using fastshap calculator example Source: https://github.com/modeloriented/shapviz/blob/main/_autodocs/_SUMMARY.txt Example of integrating shapviz with the fastshap package to calculate and visualize SHAP values. ```R library(shapviz) library(fastshap) library(xgboost) # Assume model and data are prepared # Calculate SHAP values using fastshap shap_values <- fastshap(xgb_model, X_train, "xgboost") # Create shapviz object from fastshap results sv_object <- shapviz(shap_values, X = X_train) # Visualize results sv_importance(sv_object) ``` -------------------------------- ### Feature interaction analysis example Source: https://github.com/modeloriented/shapviz/blob/main/_autodocs/_SUMMARY.txt Workflow example focusing on visualizing and analyzing feature interactions using shapviz. ```R library(shapviz) library(xgboost) # Assume xgb_model and X_train are already prepared and sv_object created # For interaction analysis, ensure SHAP interaction values are available or calculated # Example: sv_object <- shapviz(xgb_model, X_train = X_train, interactions = TRUE) # Visualize interactions sv_interaction(sv_object) ``` -------------------------------- ### Install shapviz from GitHub Source: https://github.com/modeloriented/shapviz/blob/main/README.md Installs the latest version of the shapviz package directly from its GitHub repository using the devtools package. ```r install.packages("devtools") devtools::install_github("ModelOriented/shapviz") ``` -------------------------------- ### Install shapviz from CRAN Source: https://github.com/modeloriented/shapviz/blob/main/README.md Installs the shapviz package from the Comprehensive R Archive Network (CRAN). ```r install.packages("shapviz") ``` -------------------------------- ### View all shapviz options Source: https://github.com/modeloriented/shapviz/blob/main/_autodocs/06-configuration.md Retrieve a list of all currently set global options that start with 'shapviz.' to inspect the package's configuration. ```r grep("^shapviz\.", names(options()), value = TRUE) ``` -------------------------------- ### Interactive Program Startup Notice Source: https://github.com/modeloriented/shapviz/blob/main/LICENSE.md This is an example of a short notice that an interactive program should display upon startup. It informs the user about the program's version, copyright, warranty status, and licensing terms. ```text Gnomovision version 69, Copyright (C) year name of author Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details. ``` -------------------------------- ### Configure Package Defaults Source: https://github.com/modeloriented/shapviz/blob/main/_autodocs/00-index.md Set package-wide options in .Rprofile for consistent visualization and formatting. This example sets the color palette and rounds SHAP values to two decimal places. ```r options( shapviz.viridis_args = list(option = "plasma"), shapviz.format_shap = function(z) round(z, 2) ) ``` -------------------------------- ### Example: Get Interaction Matrix Source: https://github.com/modeloriented/shapviz/blob/main/_autodocs/02-plotting-functions.md Retrieve the raw interaction matrix by calling `sv_interaction()` with `kind = "no"`. ```r # Get interaction matrix inter_mat <- sv_interaction(shp_inter, kind = "no") ``` -------------------------------- ### Fix for sv_dependence() color guide title with viridis_args = NULL Source: https://github.com/modeloriented/shapviz/blob/main/NEWS.md This bug fix addresses an issue where the color guide title was hidden when viridis_args was set to NULL in sv_dependence(). It is recommended to use viridis_args = list() instead. ```R sv_dependence(..., viridis_args = list()) ``` -------------------------------- ### Example SHAP Matrix Format Source: https://github.com/modeloriented/shapviz/blob/main/_autodocs/05-types-structures.md Illustrates the required format for a SHAP values matrix, emphasizing numeric type, required column names, and no missing values. ```r S <- matrix( c(0.5, -0.2, 0.1, -0.3, 0.8, -0.4), nrow = 3, dimnames = list( NULL, # Row names (usually NULL) c("age", "income", "credit_score") # Feature names required ) ) ``` -------------------------------- ### Reproducible analysis example Source: https://github.com/modeloriented/shapviz/blob/main/_autodocs/_SUMMARY.txt Ensures reproducibility by setting random seeds before model training and SHAP calculation. ```R library(shapviz) # Set seed for reproducibility set.seed(123) # Perform model training and SHAP calculation steps here... # Example: # sv_object <- shapviz(model, X_train) # The results should be consistent across runs if seeds are set properly. ``` -------------------------------- ### Check Optional Package Availability Source: https://github.com/modeloriented/shapviz/blob/main/_autodocs/06-configuration.md Use `requireNamespace` to check if an optional package is installed and available before attempting to use it. This is useful for conditional logic based on installed dependencies. ```r # Check if optional package available if (requireNamespace("lightgbm", quietly = TRUE)) { # Use LightGBM } ``` -------------------------------- ### Individual prediction explanation example Source: https://github.com/modeloriented/shapviz/blob/main/_autodocs/_SUMMARY.txt Demonstrates how to explain a single prediction using a waterfall plot. ```R library(shapviz) library(xgboost) # Assume sv_object is created from a model and training data # Select an instance to explain (e.g., the 5th instance) instance_id <- 5 # Generate waterfall plot for the individual prediction sv_waterfall(sv_object, instance_id) ``` -------------------------------- ### Example Feature Data Frame Format Source: https://github.com/modeloriented/shapviz/blob/main/_autodocs/05-types-structures.md Shows the required format for the feature data frame, which must match the SHAP matrix's row count and have corresponding column names. Additional columns are preserved. ```r X <- data.frame( age = c(25, 45, 65), income = factor(c("low", "medium", "high")), credit_score = c(600, 700, 750), name = c("Alice", "Bob", "Charlie") # Additional column ) # Usage shp <- shapviz(S, X) # Only age, income, credit_score used; name preserved in shapviz$X ``` -------------------------------- ### Example: Single Observation Force Plot Source: https://github.com/modeloriented/shapviz/blob/main/_autodocs/02-plotting-functions.md Visualize the SHAP force plot for a single observation using `sv_force()` with a specified `row_id`. ```r # Single observation sv_force(shp, row_id = 5) ``` -------------------------------- ### Example: Bar Plot for Interactions Source: https://github.com/modeloriented/shapviz/blob/main/_autodocs/02-plotting-functions.md Generate a bar plot for SHAP interactions by setting `kind = "bar"` and optionally `max_display` in `sv_interaction()`. ```r # Bar plot sv_interaction(shp_inter, kind = "bar", max_display = 10) ``` -------------------------------- ### Example: Average Multiple Observations Force Plot Source: https://github.com/modeloriented/shapviz/blob/main/_autodocs/02-plotting-functions.md Create an averaged force plot from multiple observations by providing a vector of `row_id` values to `sv_force()`. ```r # Average multiple sv_force(shp, row_id = c(1, 2, 3)) ``` -------------------------------- ### Example: Default Beeswarm Interaction Plot Source: https://github.com/modeloriented/shapviz/blob/main/_autodocs/02-plotting-functions.md Create a default beeswarm interaction plot using `sv_interaction()` with a shapviz object containing interaction values. ```r # Beeswarm plot sv_interaction(shp_inter) ``` -------------------------------- ### Summarize Shapviz Object Source: https://github.com/modeloriented/shapviz/blob/main/_autodocs/04-methods-operators.md Provides a detailed summary of a shapviz object, including SHAP matrix dimensions, feature data dimensions, baseline value, and the first n rows of SHAP values and corresponding feature values. Use to get a comprehensive overview of the object's content. ```r shp <- shapviz(S, X, baseline = 4) summary(shp) # 'shapviz' object representing # - SHAP matrix of dimension 2 x 2 # - feature data.frame of dimension 2 x 2 # - baseline value of 4 # # SHAP values of first 2 observations: # x y # [1,] 1 -1 # [2,]-1 1 # # Corresponding feature values: # x y # 1 a 100 # 2 b 10 ``` -------------------------------- ### XGBoost Basic Workflow Source: https://github.com/modeloriented/shapviz/blob/main/_autodocs/07-usage-patterns.md Illustrates the fundamental steps for analyzing an XGBoost model with shapviz, from data preparation and model training to creating shapviz objects and generating basic plots like feature importance and dependence. ```r library(shapviz) library(xgboost) library(ggplot2) # 1. Prepare data set.seed(1) X_train <- data.matrix(iris[, -1]) y_train <- iris[, 1] # 2. Train model dtrain <- xgb.DMatrix(X_train, label = y_train, nthread = 1) fit <- xgb.train( list(nthread = 1), data = dtrain, nrounds = 10 ) # 3. Create shapviz object shp <- shapviz(fit, X_pred = X_train, X = iris[, -1]) # 4. Create plots sv_importance(shp) sv_dependence(shp, v = "Petal.Length") sv_waterfall(shp, row_id = 1) ``` -------------------------------- ### Create a shapviz object from SHAP matrices Source: https://github.com/modeloriented/shapviz/blob/main/_autodocs/_SUMMARY.txt Shows how to initialize a shapviz object directly from SHAP matrices, which can be generated by various SHAP calculation methods. ```R library(shapviz) # Assuming 'shap_matrix' is a matrix of SHAP values and 'feature_values' are the corresponding feature values sv_object <- shapviz(shap_matrix, X = feature_values) ``` -------------------------------- ### Using Options in Shapviz Functions Source: https://github.com/modeloriented/shapviz/blob/main/_autodocs/03-extractor-utility-functions.md Illustrates how global options for shapviz can be used within functions, and how these can be overridden by providing specific arguments to the function calls. ```r sv_importance(shp, viridis_args = list(option = "viridis")) sv_waterfall(shp, format_shap = function(x) round(x, 2)) ``` -------------------------------- ### Prepare Data for SHAP Calculation with XGBoost (No Missing Values) Source: https://github.com/modeloriented/shapviz/blob/main/_autodocs/07-usage-patterns.md Demonstrates preprocessing steps to ensure data is complete (no NA values) before training an XGBoost model and creating a shapviz object. This is crucial as SHAP calculation typically requires complete data. ```r # For SHAP calculation from XGBoost: # Must use complete data (no NAs) X_train_clean <- na.omit(iris[, -1]) y_train_clean <- iris$Sepal.Length[!is.na(iris[, -1])] # Train model on clean data fit <- xgb.train(...) # Create shapviz shp <- shapviz(fit, X_pred = X_train_clean, X = X_train_clean) ``` -------------------------------- ### Get dimensions of shapviz object Source: https://github.com/modeloriented/shapviz/blob/main/_autodocs/_SUMMARY.txt Retrieves the dimensions (e.g., number of instances, features) of a shapviz object. ```R library(shapviz) # Assuming 'sv_object' is a shapviz object dim(sv_object) ``` -------------------------------- ### Initialize SHAPviz from LightGBM Model Source: https://github.com/modeloriented/shapviz/blob/main/_autodocs/01-shapviz-constructor.md Create a shapviz object from a fitted LightGBM model. Provide the model object and the data used for SHAP calculation. The 'X' parameter can be used for feature data with factors or characters. ```r library(lightgbm) X_pred <- data.matrix(iris[, -1]) dtrain <- lgb.Dataset(X_pred, label = iris[, 1]) fit <- lgb.train( params = list(objective = "regression", num_thread = 1), data = dtrain, nrounds = 10, verbose = -2 ) shp <- shapviz(fit, X_pred = X_pred) ``` -------------------------------- ### Get a specific shapviz option Source: https://github.com/modeloriented/shapviz/blob/main/_autodocs/06-configuration.md Retrieve the value of a particular shapviz global option, such as 'shapviz.viridis_args', to check its current setting. ```r getOption("shapviz.viridis_args") ``` -------------------------------- ### Multi-Output Model Analysis with mshapviz Source: https://github.com/modeloriented/shapviz/blob/main/_autodocs/07-usage-patterns.md Demonstrates how to analyze multiple target variables by training separate models, creating individual shapviz objects, and combining them into an mshapviz object for comparative analysis. ```r # Train separate models for each output fit1 <- xgb.train(...) # Model for output 1 fit2 <- xgb.train(...) # Model for output 2 # Create shapviz for each shp1 <- shapviz(fit1, X_pred = X_test) shp2 <- shapviz(fit2, X_pred = X_test) # Combine into mshapviz m_shp <- mshapviz(list( output_1 = shp1, output_2 = shp2 )) # Create combined plots sv_importance(m_shp, kind = "bar", bar_type = "dodge") sv_dependence(m_shp, v = "price") # Note: single v for mshapviz # Access individual outputs shp1_extracted <- m_shp[[1]] shp1_by_name <- m_shp[["output_1"]] ``` -------------------------------- ### Example: Limited Features Force Plot Source: https://github.com/modeloriented/shapviz/blob/main/_autodocs/02-plotting-functions.md Limit the number of features displayed in a force plot by setting the `max_display` parameter in `sv_force()`. ```r # Limited features sv_force(shp, row_id = 10, max_display = 3) ``` -------------------------------- ### Create shapviz Object from LightGBM Model Source: https://github.com/modeloriented/shapviz/blob/main/_autodocs/07-usage-patterns.md Visualize SHAP explanations for a LightGBM model using shapviz. This involves training a LightGBM model and then passing the model object to shapviz. ```r library(lightgbm) library(shapviz) # Train LightGBM model fit <- lgb.train( params = list(objective = "regression"), data = lgb.Dataset(X_train, label = y_train), nrounds = 10 ) # Create shapviz shp <- shapviz(fit, X_pred = X_train) # Plots sv_importance(shp) ``` -------------------------------- ### shapviz.explain() Source: https://github.com/modeloriented/shapviz/blob/main/_autodocs/01-shapviz-constructor.md Creates a shapviz object from the output of fastshap::explain(). It requires the explain output and optionally accepts feature values, a baseline, and parameters for collapsing SHAP columns. ```APIDOC ## shapviz.explain() ### Description Creates a shapviz object from the output of fastshap::explain(). It requires the explain output and optionally accepts feature values, a baseline, and parameters for collapsing SHAP columns. ### Method `shapviz.explain(object, X = NULL, baseline = NULL, collapse = NULL, ...)` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```r library(fastshap) # fastshap::explain() with shap_only = FALSE ex <- fastshap::explain(model, X = X_train) shp <- shapviz(ex) # fastshap::explain() with shap_only = TRUE ex <- fastshap::explain(model, X = X_train, shap_only = TRUE) shp <- shapviz(ex, X = X_train, baseline = attr(ex, "baseline")) ``` ### Response #### Success Response (200) `shapviz` object #### Response Example None provided in source. ``` -------------------------------- ### Get dimension names of shapviz object Source: https://github.com/modeloriented/shapviz/blob/main/_autodocs/_SUMMARY.txt Retrieves the dimension names (e.g., instance names, feature names) from a shapviz object. ```R library(shapviz) # Assuming 'sv_object' is a shapviz object dimnames(sv_object) ``` -------------------------------- ### Initialize SHAPviz from XGBoost Model (Binary/Regression) Source: https://github.com/modeloriented/shapviz/blob/main/_autodocs/01-shapviz-constructor.md Create a shapviz object directly from a fitted XGBoost model. Provide the model object and the data used for prediction. The 'X' parameter can be used to supply feature data with factors or characters for visualization. ```r library(xgboost) # Binary/regression model X_pred <- data.matrix(iris[, -1]) dtrain <- xgb.DMatrix(X_pred, label = iris[, 1], nthread = 1) fit <- xgb.train(list(nthread = 1), data = dtrain, nrounds = 10) # Use numeric matrix for visualization shp <- shapviz(fit, X_pred = X_pred) # Use original data with factors for visualization shp <- shapviz(fit, X_pred = X_pred, X = iris) ``` -------------------------------- ### Shapviz Dependence Plot Examples Source: https://github.com/modeloriented/shapviz/blob/main/_autodocs/02-plotting-functions.md Visualize the relationship between a feature and SHAP values. Supports coloring by a third variable and plotting multiple features. ```r sv_dependence(shp, v = "Petal.Length", color_var = "Species") ``` ```r sv_dependence(shp, v = "Petal.Length", color_var = NULL) ``` ```r sv_dependence(shp, v = c("Petal.Length", "Sepal.Width"), share_y = TRUE) ``` ```r shp_inter <- shapviz(fit, X_pred = X_train, X = iris, interactions = TRUE) sv_dependence(shp_inter, v = "Petal.Length", interactions = TRUE) ``` -------------------------------- ### Retrieving Global Shapviz Options Source: https://github.com/modeloriented/shapviz/blob/main/_autodocs/03-extractor-utility-functions.md Shows how to retrieve the current global options set for shapviz using `getOption`. This is useful for inspecting or confirming current settings. ```r getOption("shapviz.viridis_args") getOption("shapviz.format_shap") getOption("shapviz.format_feat") ``` -------------------------------- ### Sample Shapviz Object Source: https://github.com/modeloriented/shapviz/blob/main/_autodocs/07-usage-patterns.md Sample data before or after creating a shapviz object to manage memory or focus analysis. Use `shapviz()` for initial sampling or subsetting the created object. ```r # Sample before SHAP calculation if possible sample_idx <- sample(nrow(X_train), 5000) shp <- shapviz(fit, X_pred = X_train[sample_idx, ], X = X_train[sample_idx, ]) # Or: Sample shapviz object after creation shp_sample <- shp[sample(nrow(shp), 1000), ] ``` -------------------------------- ### Getting feature names from shapviz object Source: https://github.com/modeloriented/shapviz/blob/main/NEWS.md Use the colnames() function on a 'shapviz' object to retrieve the names of the features. This is analogous to using dimnames(). ```R colnames(x) ``` -------------------------------- ### SHAPVIZ Constructor Functions Source: https://github.com/modeloriented/shapviz/blob/main/_autodocs/_SUMMARY.txt Functions for creating SHAPVIZ objects, supporting multiple input types including SHAP matrices, various model objects (XGBoost, LightGBM, H2O), and results from different SHAP calculation methods. Also includes `mshapviz()` for combining objects. ```APIDOC ## shapviz() ### Description Constructor function for creating SHAPVIZ objects. It supports a wide range of input types for SHAP values and model objects. ### Method `shapviz(x, ...)` ### Parameters - **x**: (Various) The primary input object, which can be a SHAP matrix, a model object (XGBoost, LightGBM, H2O, etc.), or results from other SHAP calculators (fastshap, treeshap, DALEX, shapr, kernelshap/permshap). - **...**: Additional arguments passed to specific methods. ### Endpoint N/A (R function) ### Response - **shapviz object**: A structured object for visualization and analysis. ## mshapviz() ### Description Function for combining multiple SHAPVIZ objects into a single object, useful for multi-model or multi-class analyses. ### Method `mshapviz(x, ...)` ### Parameters - **x**: (shapviz or list of shapviz) The SHAPVIZ object(s) to combine. - **...**: Additional arguments passed to specific methods. ### Endpoint N/A (R function) ### Response - **mshapviz object**: A combined SHAPVIZ object. ``` -------------------------------- ### XGBoost with SHAP Interactions Source: https://github.com/modeloriented/shapviz/blob/main/_autodocs/07-usage-patterns.md Demonstrates how to enable SHAP interactions during shapviz object creation and visualize interaction effects using plots like sv_interaction and sv_dependence. ```r shp_inter <- shapviz( fit, X_pred = X_train, X = iris[, -1], interactions = TRUE ) # Interaction plot sv_interaction(shp_inter, kind = "bar", max_display = 5) # Dependence with interactions sv_dependence(shp_inter, v = "Petal.Length", interactions = TRUE) # Get interaction matrix inter_mat <- sv_interaction(shp_inter, kind = "no") ``` -------------------------------- ### shapviz.lgb.Booster() - From LightGBM Model Source: https://github.com/modeloriented/shapviz/blob/main/_autodocs/01-shapviz-constructor.md Initializes a shapviz object from a fitted LightGBM model. It calculates SHAP values internally using the provided prediction data. ```APIDOC ## shapviz.lgb.Booster() - From LightGBM Model ### Description Initializes a shapviz object from a fitted LightGBM model. It calculates SHAP values internally using the provided prediction data. ### Parameters #### Path Parameters - **object** (lgb.Booster) - Required - Fitted LightGBM model - **X_pred** (matrix) - Required - Data for SHAP calculation (must have column names) #### Query Parameters - **X** (matrix, data.frame) - Optional - Default: X_pred - Feature data for visualization - **which_class** (integer, NULL) - Optional - Default: NULL - For multiclass: which class (≥ 1). NULL returns mshapviz - **collapse** (list, NULL) - Optional - Default: NULL - Named list to combine SHAP columns ### Request Example ```r library(lightgbm) X_pred <- data.matrix(iris[, -1]) dtrain <- lgb.Dataset(X_pred, label = iris[, 1]) fit <- lgb.train( params = list(objective = "regression", num_thread = 1), data = dtrain, nrounds = 10, verbose = -2 ) shp <- shapviz(fit, X_pred = X_pred) ``` ### Response `shapviz` object (or `mshapviz` if multiclass with which_class = NULL) ``` -------------------------------- ### Get Names and Length of mshapviz Object Source: https://github.com/modeloriented/shapviz/blob/main/_autodocs/05-types-structures.md Retrieves the names assigned to the elements within an mshapviz object and the total number of contained shapviz objects. ```r # List extraction names(m_shp) # [1] "obs1" "obs2" length(m_shp) # [1] 2 ``` -------------------------------- ### Setting Global Shapviz Options Source: https://github.com/modeloriented/shapviz/blob/main/_autodocs/03-extractor-utility-functions.md Demonstrates how to set global options for shapviz, affecting default behavior for visualizations and formatting. These options can be overridden at the function level. ```r options( shapviz.viridis_args = list(begin = 0.25, end = 0.85, option = "inferno"), shapviz.format_shap = function(z) prettyNum(z, digits = 3, scientific = FALSE), shapviz.format_feat = function(z) prettyNum(z, digits = 3, scientific = FALSE) ) ``` -------------------------------- ### Basic Usage with XGBoost and Diamonds Dataset Source: https://github.com/modeloriented/shapviz/blob/main/README.md Demonstrates fitting an XGBoost model to predict diamond prices and generating SHAP importance and dependence plots using shapviz. ```r library(shapviz) library(ggplot2) library(xgboost) set.seed(1) xvars <- c("log_carat", "cut", "color", "clarity") X <- diamonds |> transform(log_carat = log(carat)) |> subset(select = xvars) # Fit (untuned) model fit <- xgb.train( params = list(learning_rate = 0.1), data = xgb.DMatrix(data.matrix(X), label = log(diamonds$price)), nrounds = 65 ) # SHAP analysis: X can even contain factors X_explain <- X[sample(nrow(X), 2000), ] shp <- shapviz(fit, X_pred = data.matrix(X_explain), X = X_explain) sv_importance(shp, show_numbers = TRUE) sv_importance(shp, kind = "bee") sv_dependence(shp, v = xvars, share_y = TRUE) ``` -------------------------------- ### Get Dimension Names of Shapviz Object Source: https://github.com/modeloriented/shapviz/blob/main/_autodocs/04-methods-operators.md Retrieves the row and column names of the SHAP matrix in a shapviz object. Use `colnames()` for direct access to feature names. ```r shp <- shapviz(S, X) dimnames(shp) # [[1]] # NULL # # [[2]] # [1] "x" "y" colnames(shp) # [1] "x" "y" ``` -------------------------------- ### Create shapviz from shapr::explain() Results Source: https://github.com/modeloriented/shapviz/blob/main/_autodocs/01-shapviz-constructor.md Construct a shapviz object from the output of shapr::explain(). The feature values are usually inferred from the input object. ```r library(shapr) ex <- shapr::explain(model, X = X_train, ...) shp <- shapviz(ex) ``` -------------------------------- ### Subset Data for Visualization Source: https://github.com/modeloriented/shapviz/blob/main/_autodocs/06-configuration.md Reduce the number of observations in a SHAP object before plotting to improve performance and visual clarity when dealing with large datasets. This example subsets to 1000 observations. ```r # Subset for visualization shp_sample <- shp[sample(nrow(shp), 1000), ] sv_importance(shp_sample, max_display = 20) ``` -------------------------------- ### Get Dimensions of Shapviz Object Source: https://github.com/modeloriented/shapviz/blob/main/_autodocs/04-methods-operators.md Retrieves the dimensions (number of rows and columns) of the SHAP matrix within a shapviz object. Use `nrow()` and `ncol()` for individual dimension access. ```r shp <- shapviz(S, X) dim(shp) # [1] 2 2 nrow(shp) # [1] 2 col(shp) # [1] 2 ``` -------------------------------- ### Create shapviz Object from fastshap Explainer Source: https://github.com/modeloriented/shapviz/blob/main/_autodocs/07-usage-patterns.md Integrate shapviz with the fastshap package. This snippet shows how to create a fastshap explainer object and then use it to initialize a shapviz object for visualization. ```r library(fastshap) library(shapviz) # Create explainer ex <- fastshap::explain( fit, X = X_train, nsim = 10, pred_wrapper = predict ) # Create shapviz (ex$shapley_values extracted automatically) shp <- shapviz(ex) # Plots sv_importance(shp) ``` -------------------------------- ### Select and Analyze Top Features with Shapviz Source: https://github.com/modeloriented/shapviz/blob/main/_autodocs/07-usage-patterns.md Identify and subset the most important features for detailed analysis. This involves getting feature importances, selecting top features, and then subsetting the shapviz object. ```r # Select important features for detailed analysis imp <- sv_importance(shp, kind = "no") top_features <- names(imp)[1:10] # Subset shapviz shp_top <- shp[, top_features] sv_interaction(shp_top, interactions = TRUE) ``` -------------------------------- ### Constructor Functions Source: https://github.com/modeloriented/shapviz/blob/main/_autodocs/00-index.md Functions to create shapviz objects from different data sources and model types. ```APIDOC ## Constructor Functions - `shapviz()` - Generic constructor - `shapviz.matrix(object, ..., baseline = NULL, collapse = NULL, which_class = NULL)` - Constructor for SHAP matrix and features. - `shapviz.xgb.Booster(object, ..., baseline = NULL, collapse = NULL, which_class = NULL)` - Constructor for XGBoost models. - `shapviz.lgb.Booster(object, ..., baseline = NULL, collapse = NULL, which_class = NULL)` - Constructor for LightGBM models. - `shapviz.H2OModel(object, ..., baseline = NULL, collapse = NULL, which_class = NULL)` - Constructor for H2O models. - `shapviz.explain(object, ..., baseline = NULL, collapse = NULL, which_class = NULL)` - Constructor for fastshap results. - `mshapviz(object, ..., baseline = NULL, collapse = NULL, which_class = NULL)` - Combine multiple shapviz objects. ``` -------------------------------- ### Get Feature Importance Values Source: https://github.com/modeloriented/shapviz/blob/main/_autodocs/02-plotting-functions.md Retrieves the raw feature importance values as a named numeric vector. Use when you need the numerical data for further analysis or custom plotting. Requires a shapviz object. ```R imp_values <- sv_importance(x, kind = "no") ``` -------------------------------- ### Create Minimal shapviz Object Source: https://github.com/modeloriented/shapviz/blob/main/_autodocs/05-types-structures.md Constructs a basic shapviz object with SHAP values, feature values, and a baseline. Ensure column names match between S and X. ```r S <- matrix(c(1, -1, -1, 1), ncol = 2, dimnames = list(NULL, c("x", "y"))) X <- data.frame(x = c("a", "b"), y = c(100, 10)) shp <- shapviz(S, X, baseline = 4) str(shp) # List of 4 # $ S : num [1:2, 1:2] 1 -1 -1 1 # ..- attr(*, "dimnames")=List of 2 # .. ..$ : NULL # .. ..$ : chr [1:2] "x" "y" # $ X :'data.frame': 2 obs. of 2 variables: # ..$ x: chr [1:2] "a" "b" # ..$ y: num [1:2] 100 10 # $ baseline: num 4 # $ S_inter : NULL # - attr(*, "class")= chr "shapviz" ``` -------------------------------- ### Standard Software License Header Source: https://github.com/modeloriented/shapviz/blob/main/LICENSE.md This is a template for the header to be included at the beginning of each source file when distributing software under the GNU General Public License. It includes copyright information and a pointer to the full license. ```text Copyright (C) This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. ``` -------------------------------- ### Set Baseline Value for SHAP Visualization Source: https://github.com/modeloriented/shapviz/blob/main/_autodocs/05-types-structures.md Defines a single numeric baseline value, representing the average prediction. This serves as the starting point for plots like waterfall and force plots. It must be on the same scale as SHAP values. ```r # From XGBoost # Baseline is extracted automatically from predict(predcontrib=TRUE) output # From matrix baseline <- 0.5 # Middle probability for binary classification shp <- shapviz(S, X, baseline = baseline) # Access get_baseline(shp) # 0.5 ``` -------------------------------- ### Create a shapviz object from an XGBoost model Source: https://github.com/modeloriented/shapviz/blob/main/_autodocs/_SUMMARY.txt Demonstrates creating a shapviz object using the shapviz() constructor with an XGBoost model. Supports binary and multiclass classification. ```R library(shapviz) # Assuming 'xgb_model' is a trained XGBoost model and 'train_data' is the training data sv_object <- shapviz(xgb_model, X_train = train_data) ``` -------------------------------- ### Set global option for viridis palettes Source: https://github.com/modeloriented/shapviz/blob/main/_autodocs/_SUMMARY.txt Configures default color palette arguments for viridis using the global option shapviz.viridis_args. ```R library(shapviz) # Set custom viridis arguments options(shapviz.viridis_args = list(option = "C")) ``` -------------------------------- ### Create shapviz from fastshap::explain() Results Source: https://github.com/modeloriented/shapviz/blob/main/_autodocs/01-shapviz-constructor.md Use this constructor for SHAP values generated by fastshap::explain(). It can handle results where SHAP values are calculated directly or when only SHAP values are provided. ```r library(fastshap) # fastshap::explain() with shap_only = FALSE ex <- fastshap::explain(model, X = X_train) shp <- shapviz(ex) # fastshap::explain() with shap_only = TRUE ex <- fastshap::explain(model, X = X_train, shap_only = TRUE) shp <- shapviz(ex, X = X_train, baseline = attr(ex, "baseline")) ``` -------------------------------- ### Creating mshapviz object with mshapviz() Source: https://github.com/modeloriented/shapviz/blob/main/NEWS.md Create an 'mshapviz' object by passing a named list of 'shapviz' objects to the mshapviz function. This is an alternative to using c(). ```R mshapviz(list(Mod_1 = s1, Mod_2 = s2, ...)) ``` -------------------------------- ### Create shapviz from H2O Model Source: https://github.com/modeloriented/shapviz/blob/main/_autodocs/01-shapviz-constructor.md Construct a shapviz object from a fitted H2O model. Requires the h2o package to be loaded and initialized. ```r library(h2o) h2o.init() X_pred <- as.data.frame(iris[, -1]) fit <- h2o.train(...) # H2O model shp <- shapviz(fit, X_pred = X_pred) ``` -------------------------------- ### Create shapviz from LightGBM Model Source: https://github.com/modeloriented/shapviz/blob/main/_autodocs/01-shapviz-constructor.md Use this constructor when your fitted model is a LightGBM object. Ensure the data used for prediction matches the training data format. ```r params <- list(objective = "multiclass", num_class = 3, num_thread = 1) X_pred <- data.matrix(iris[, -5]) dtrain <- lgb.Dataset(X_pred, label = as.integer(iris[, 5]) - 1) fit <- lgb.train(params = params, data = dtrain, nrounds = 10) shp_multi <- shapviz(fit, X_pred = X_pred) ``` -------------------------------- ### Visualizing SHAP Interaction Effects Source: https://github.com/modeloriented/shapviz/blob/main/_autodocs/07-usage-patterns.md Demonstrates how to analyze and visualize pure feature interaction effects using shapviz, including generating interaction matrices and dependence plots that highlight interaction-only contributions. ```r shp_inter <- shapviz(fit, X_pred = X_test, interactions = TRUE) # Interaction strength matrix inter_mat <- sv_interaction(shp_inter, kind = "no") # Shows average absolute interactions between all feature pairs # Visualize sv_interaction(shp_inter, kind = "beeswarm") # Pure interaction effects (excluding main effects) sv_dependence( shp_inter, v = "Petal.Length", color_var = "Species", interactions = TRUE # Shows interaction only, not main effects ) ``` -------------------------------- ### S3 Methods and Operators Source: https://github.com/modeloriented/shapviz/blob/main/_autodocs/_SUMMARY.txt Documentation for S3 methods and operators that can be applied to SHAPVIZ objects, enabling standard R object manipulation like printing, summarizing, subsetting, and combining. ```APIDOC ## S3 Methods for shapviz Objects ### Description This section documents the S3 methods and operators that are implemented for `shapviz` and `mshapviz` objects, allowing for standard R data manipulation and inspection. ### Methods and Operators - **`print(x, ...)`**: Displays a summary or representation of the `shapviz` object. - **`summary(x, ...)`**: Provides a detailed summary of the `shapviz` object. - **`dim(x)`**: Returns the dimensions of the SHAP object (e.g., number of observations, features). - **`dimnames(x)`**: Returns the names of dimensions (e.g., feature names). - **`x[i, j, ...]`**: Subsetting operator to select parts of the `shapviz` object. - **`x + y`**: Combines two `shapviz` objects using addition. - **`rbind(x, y, ...)`**: Row-binds multiple `shapviz` objects. - **`c(x, y, ...)`**: Concatenates `shapviz` objects. - **`split(x, f, ...)`**: Splits a `shapviz` object based on a factor `f`. ### Parameters - **x, y**: (shapviz or mshapviz) The objects to operate on. - **i, j**: Indices for subsetting. - **f**: Factor for splitting. - **...**: Additional arguments passed to underlying methods. ### Endpoint N/A (R methods) ### Response - Varies depending on the method (e.g., object representation, summary statistics, subsetted object, combined object). ``` -------------------------------- ### XGBoost Multiclass Model Analysis Source: https://github.com/modeloriented/shapviz/blob/main/_autodocs/07-usage-patterns.md Shows how to train a multiclass XGBoost model and create shapviz objects for individual classes or combine them using mshapviz for aggregated analysis and plotting. ```r # Train multiclass model params <- list(objective = "multi:softprob", num_class = 3, nthread = 1) X_pred <- data.matrix(iris[, -5]) y_pred <- as.integer(iris[, 5]) - 1 dtrain <- xgb.DMatrix(X_pred, label = y_pred, nthread = 1) fit <- xgb.train(params = params, data = dtrain, nrounds = 10) # Create shapviz for each class shp_1 <- shapviz(fit, X_pred = X_pred, which_class = 1) shp_2 <- shapviz(fit, X_pred = X_pred, which_class = 2) # Or create mshapviz with all classes shp_multi <- shapviz(fit, X_pred = X_pred) # Plot all classes together sv_importance(shp_multi, kind = "bar", bar_type = "dodge") ``` -------------------------------- ### Initialize SHAPviz from XGBoost Multiclass Model (Single Class) Source: https://github.com/modeloriented/shapviz/blob/main/_autodocs/01-shapviz-constructor.md For multiclass XGBoost models, specify 'which_class' to generate a shapviz object for a specific class. The 'X_pred' should be data for SHAP calculation, and 'X' can be the original feature data. ```r # Multiclass model - get one class params <- list(objective = "multi:softprob", num_class = 3, nthread = 1) X_pred <- data.matrix(iris[, -5]) dtrain <- xgb.DMatrix(X_pred, label = as.integer(iris[, 5]) - 1, nthread = 1) fit <- xgb.train(params = params, data = dtrain, nrounds = 10) shp <- shapviz(fit, X_pred = X_pred, which_class = 2) ``` -------------------------------- ### shapviz.shapr() Source: https://github.com/modeloriented/shapviz/blob/main/_autodocs/01-shapviz-constructor.md Creates a shapviz object from the results of shapr::explain(). It takes the shapr object and optionally allows specifying feature values and collapsing SHAP columns. ```APIDOC ## shapviz.shapr() ### Description Creates a shapviz object from the results of shapr::explain(). It takes the shapr object and optionally allows specifying feature values and collapsing SHAP columns. ### Method `shapviz.shapr(object, X = as.data.frame(object$internal$data$x_explain), collapse = NULL, ...)` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```r library(shapr) ex <- shapr::explain(model, X = X_train, ...) shp <- shapviz(ex) ``` ### Response #### Success Response (200) `shapviz` object #### Response Example None provided in source. ``` -------------------------------- ### Methods and Operators Source: https://github.com/modeloriented/shapviz/blob/main/_autodocs/00-index.md Methods and operators for subsetting, combining, and summarizing shapviz objects. ```APIDOC ## Methods and Operators - `print(object)` - Display a shapviz object. - `summary(object)` - Summarize a shapviz object. - `dim(object)` - Get the dimensions of the object. - `dimnames(object)` - Get the dimension names of the object. - `object[rows, cols]` - Subset the object by rows and columns. - `object1 + object2` - Combine rows of two shapviz objects. - `rbind(object1, object2, ...)` - Bind rows of shapviz objects. - `c(object1, object2, ...)` - Concatenate shapviz objects. - `split(object, factor)` - Split a shapviz object by a factor. ``` -------------------------------- ### Create mshapviz Object using c() Source: https://github.com/modeloriented/shapviz/blob/main/_autodocs/05-types-structures.md An alternative method to create an mshapviz object by concatenating shapviz objects. Useful for combining multiple outputs. ```r # Or via c() m_shp <- c(obs1 = s1, obs2 = s2) ``` -------------------------------- ### Create shapviz from DALEX::predict_parts() Results Source: https://github.com/modeloriented/shapviz/blob/main/_autodocs/01-shapviz-constructor.md Use this constructor for SHAP results obtained from DALEX::predict_parts(). Ensure the 'type' argument was set to 'shap' during prediction. ```r library(DALEX) pp <- predict_parts(model_explainer, new_observation = X, type = "shap") shp <- shapviz(pp) ``` -------------------------------- ### Creating mshapviz object from multiclass/multioutput kernelshap Source: https://github.com/modeloriented/shapviz/blob/main/NEWS.md Create an 'mshapviz' object directly from a multiclass or multioutput 'kernelshap' object. This simplifies working with multiple SHAP visualizations. ```R shapviz(kernelshap_object) ``` -------------------------------- ### print.shapviz() Source: https://github.com/modeloriented/shapviz/blob/main/_autodocs/04-methods-operators.md Prints a shapviz object, displaying its SHAP matrix dimensions and the first two rows. It invisibly returns the object itself. ```APIDOC ## print.shapviz() ### Description Prints a shapviz object, displaying its SHAP matrix dimensions and the first two rows. It invisibly returns the object itself. ### Signature ```r print.shapviz(x, ...) ``` ### Parameters #### Parameters - **x** (shapviz) - Required - Object to print - **...** (—) - Optional - Further arguments (unused) ### Returns Invisibly returns `x`. ### Output Displays SHAP matrix dimensions and first 2 rows. ### Example ```r shp <- shapviz(S, X, baseline = 4) print(shp) # 'shapviz' object representing 2 x 2 SHAP matrix. Top lines: # # x y # [1,] 1 -1 # [2,]-1 1 ``` ``` -------------------------------- ### Initialize mSHAPviz from XGBoost Multiclass Model (All Classes) Source: https://github.com/modeloriented/shapviz/blob/main/_autodocs/01-shapviz-constructor.md When 'which_class' is NULL for a multiclass XGBoost model, shapviz returns an 'mshapviz' object containing SHAP values for all classes. ```r # Multiclass model - get all classes as mshapviz shp_multi <- shapviz(fit, X_pred = X_pred) ```