Workaround "n.trees" is missing in R package gbm version 2.1.1

Just short note to anyone encountering following error in the gbm package version 2.1.1:

 Error in paste("Using", n.trees, "trees...\n") : 
  argument "n.trees" is missing, with no default 

This issue will be fixed in the next version but in the mean time I'll post my workaround. If you add following function to your code then everything should work:


## work around bug in gbm 2.1.1
predict.gbm <- function (object, newdata, n.trees, type = "link", single.tree = FALSE, ...) {
  if (missing(n.trees)) {
    if (object$train.fraction < 1) {
      n.trees <- gbm.perf(object, method = "test", plot.it = FALSE)
    }
    else if (!is.null(object$cv.error)) {
      n.trees <- gbm.perf(object, method = "cv", plot.it = FALSE)
    }
    else {
      n.trees <- length(object$train.error)
    }
    cat(paste("Using", n.trees, "trees...\n"))
    gbm::predict.gbm(object, newdata, n.trees, type, single.tree, ...)
  }
}

2 comments:

Katie said...

This worked for me, thank you! I was getting the error when trying to plot a 3D two way interaction from a gbm model using visreg2d in the visreg package.

Tiago Fardilha said...

Worked for me too. Thanks a lot.