Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Implement additive force plots #7

Closed
bgreenwell opened this issue Jan 6, 2020 · 1 comment
Closed

Implement additive force plots #7

bgreenwell opened this issue Jan 6, 2020 · 1 comment

Comments

@bgreenwell
Copy link
Owner

@bgreenwell bgreenwell commented Jan 6, 2020

See here for examples. Here's a cheap hack using reticulate:

force_plot <- function(object, ...) {
  UseMethod("force_plot")
}

force_plot.explain <- function(object, prediction = NULL, baseline = NULL, 
                               feature_values = NULL,...) {
  object <- (object / sum(object)) * (prediction - baseline)
  shap <- reticulate::import("shap")
  fp <- shap$force_plot(
    base_value = baseline, 
    shap_values = data.matrix(object),
    features = data.matrix(feature_values),
    feature_names = names(object),
    matplotlib = FALSE,
    ...
  )
  tfile <- tempfile(fileext = ".html")
  shap$save_html(tfile, plot_html = fp)
  # Check for dependency
  if (requireNamespace("rstudioapi", quietly = TRUE)) {
    rstudioapi::viewer(tfile)
  } else if (requireNamespace("utils", quietly = TRUE)) {
    utils::browseURL(tfile)
  } else {
    stop("Packages \"rstudioapi\" or \"utils\" needed for this function to ",
         "work. Please install one of them.", call. = FALSE)
  }
}
@bgreenwell
Copy link
Owner Author

@bgreenwell bgreenwell commented Jan 6, 2020

Minimal example:

# Load required packages
library(fastshap)  # for fast (approximate) Shapley values
library(mlbench)   # for Friedman 1 benchmark data set
library(ranger)    # for fast random forest algorithm

# Simulate training data
set.seed(101)
trn <- as.data.frame(mlbench.friedman1(3000))
X <- subset(trn, select = -y)  # feature columns only

# Fit a random forest
set.seed(102)
rfo <- ranger(y ~ ., data =  trn)

# Prediction wrapper
pfun <- function(object, newdata) {
  predict(object, data = newdata)$predictions
}

# Compute fast (approximate) Shapley values using 10 Monte Carlo repetitions
system.time({  # estimate run time
  set.seed(5038)
  ex <- explain(rfo, X = X, pred_wrapper = pfun, nsim = 10)
})

# Construct force plot
force_plot(ex[1, ], prediction = pfun(rfo, X[1, ]), 
           baseline = mean(pfun(rfo, X)), feature_values = X[1, ])

Screen Shot 2020-01-06 at 2 23 21 PM

@bgreenwell bgreenwell closed this Jan 10, 2020
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Linked pull requests

Successfully merging a pull request may close this issue.

None yet
1 participant
You can’t perform that action at this time.