'fastshap: Error in UseMethod("explain") : no applicable method for 'explain' applied to an object of class "xgb.Booster"

After fitting a xgboost model (model_n) I try to run the code below to obtain shap-values, where trainval is a dataframe with my traindata without the Y variabele:

shap_values <- explain(model_n, X = trainval)

I receive this error:

[[Error in UseMethod("explain") : 
  no applicable method for 'explain' applied to an object of class ["xgb.Booster"]]

If I use this line:

shap_values <- fastshap::explain(model_n, X = trainval)

I receive this error:

Error in explain.default(object, feature_names = feature_names, X = X,  : 
  argument "pred_wrapper" is missing, with no default

I have also tried with trainval as a matrix although this gives the same error.

Any idea what could be the cause?

Thanks a lot!



Solution 1:[1]

Adding library(vip) besides library(fastshap) to my code did solve the issue for using shap_values <- fastshap::explain(model_n, X = trainval)

Solution 2:[2]

fastshap is a good tool, but not a super-easy one. You need to pass a prediction function called pred_wrap so the fastshap explainer knows how to generate new predictions from your model.

Example code taken from https://bgreenwell.github.io/fastshap/articles/fastshap.html :

# 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)
  shap <- explain(rfo, X = X, pred_wrapper = pfun, nsim = 10)
})

Also, if you are working with xgboost specifically the SHAPforxgboost package may be friendlier: https://liuyanguu.github.io/post/2019/07/18/visualization-of-shap-for-xgboost/

Finally the vip package is not a replacement for fastshap. It's a framework which contains many variable importance metrics and plots for them. Including, but not limited to shapley.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 user2165379
Solution 2 madprogramer