Solved – how to plot 3D partial dependence in GBM

boostingnon-independentpartial-effect

I can use the following code to get one-dimensional partial dependence plot. what code can I plot two-variable partial dependence plot, that's the three dimensional figure. Thanks.

plot.gbm(GBMmodel,i.var=4,n.trees=100…)

Best Answer

You can use the R function persp.

Here is an example using diabetes dataset along with the function reshape2::acast to convert a three columns dataframe into a matrix of desired dimension.

We represent the partial dependence plot of the variables age and sex.

library(gbm)
library(reshape2)
data(diabetes, package = 'lars')

y        <- diabetes$y
x        <- diabetes$x
class(x) <- 'matrix'
data     <- data.frame(y, as.data.frame(x))

gbm.model <- gbm::gbm(formula = y ~ . , data = data, distribution = 'gaussian', 
                 shrinkage = 1, bag.fraction = 1, n.trees = 100,
                 interaction.depth = 3, verbose = T, keep.data = F)


partial <- plot(gbm.model, i.var = c(1,2), return.grid = T)

colnames(partial)

mat <- reshape2::acast(data = partial, formula = age ~ sex, value.var = 'y')

persp(x = as.numeric(colnames(mat)), y = as.numeric(rownames(mat)), z=mat,
      zlab = 'partial dependence', xlab = 'sex', ylab = 'age', theta = 30)

We obtain the following plot : enter image description here