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, ...)
  }
}

4 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.

Tiny Ocean said...

Thanks.
I suggest add
else {
gbm::predict.gbm(object, newdata, n.trees, type, single.tree, ...)
}
outside the if clause so it will work in any situation.

Besides, I noticed that
"X-CRAN-Comment: Orphaned on 2017-03-21 as long-standing errors were not
corrected. NMU by CRAN team."
from the help page of gbm-package of the newest released version 2.1.3.
You mentioned above that "This issue will be fixed in the next version", so do you have any idea about the active maintainer of "gbm"? Or is there a community that I could know the current bugs? Thanks.

Samuel Bosch said...

I'm afraid maxlike is no longer actively supported.