# Install required libraries install.packages("ranger") install.packages("iml") # Load the libraries library(ranger) library(iml) # Define the target targetTag <- "Petal.Width" # Training dataset irisNUM <- iris[2:nrow(iris), 1:(ncol(iris) - 1)] # Record to explain using Shapley values irisNUM_explain <- iris[1, 1:3] # Adjust the weights based on recent observations, to give it more weight weight <- c(1:nrow(irisNUM)) weight <- round(exp(weight / (length(weight) / 3)), digits = 1) # Define the formula for the model targetForm <- paste(targetTag, " ~ .", sep = "") # Train the model set.seed(123) model <- ranger(as.formula(targetForm), data = irisNUM, write.forest = TRUE, min.node.size = 25, case.weights = weight, seed = 123) # Create custom function for the predictor predFunction <- function(object, newdata) predict(object, data = newdata)$predictions # Create the predictor predictor <- Predictor$new(model = model, data = irisNUM[ , 1:3], y = irisNUM[ , targetTag], predict.function = predFunction) # Calculater the shapley values shapley <- Shapley$new(predictor, x.interest = irisNUM_explain) # Sum of Shapley values SHAP_sum <- sum(shapley$results$phi) # The difference the sum of Shapley values should be equal to diff <- shapley$y.hat.interest - shapley$y.hat.average # Final check, must be TRUE SHAP_sum == diff