Search code examples
rshap

R: How to calculate and plot SHAP interaction values?


It is pretty easy to compute and plot SHAP interaction values with Python: https://h1ros.github.io/posts/explain-the-interaction-values-by-shap/ or https://towardsdatascience.com/analysing-interactions-with-shap-8c4a2bc11c2a

I would like to do the same in R, preferably by using the packages kernelshap (compute SHAP values ) and shapviz (visualize SHAP). However, I struggle to find the equivalent for computing SHAP interaction values and how to plot them--can anyone please help?


Solution

  • Edit

    The 0.5.0 release of "shapviz" now offers plots for SHAP interactions calculated from XGBoost models or "treeshap":

    library(shapviz)
    library(xgboost)
    
    dtrain <- xgb.DMatrix(data.matrix(iris[, -1]), label = iris[, 1])
    fit <- xgb.train(data = dtrain, nrounds = 50)
    x2 <- shapviz(fit, X_pred = dtrain, X = iris, interactions = TRUE)
    sv_dependence(x2, "Petal.Length", interactions = TRUE)
    sv_dependence(x2, "Petal.Length", color_var = "auto", interactions = TRUE)
    sv_interaction(x2)
    

    enter image description here enter image description here enter image description here

    Original answer

    You can calculate SHAP values with packages "xgboost" and "treeshap" (and then plot them e.g. with "ggplot2".)

    Example with XGBoost: predict(..., predinteraction=TRUE)

    • Integration into "shapviz" is on the roadmap, and I will start to add such plots very soon): https://github.com/mayer79/shapviz/issues/6 (I will add your links)
    • AFAIK, there is no theory yet of how to calculate Kernel SHAP interactions. Any reference is highly appreciated.