1

Can anybody explain why predict does not work with speedglm?

Working code:

library(speedglm)
mtcars2<-mtcars
mtcars2$gear<-as.factor(mtcars2$gear)
mtcars_train<-mtcars2[1:10,]
mtcars_test<-mtcars2[11:nrow(mtcars2),]
model<-speedglm(formula = cyl ~ gear,data = mtcars_train,family=poisson(link="log"))
pred<-predict(object = model, newdata = mtcars_test)
pred

I get only NA's.

Is it possible to modify the class of the glm object such that it uses the regular predict function? I mean, the speedglm object is the same form as a regular glm object, right?

class(model)
#[1] "speedglm" "speedlm" 
patL
  • 2,259
  • 1
  • 17
  • 38
HeyJane
  • 143
  • 4
  • No, you can't just change the class and expect it to work. The object is missing components needed by `predict.glm`. Also, the documentation says that `predict.speedglm` is "under construction". I suggest that you calculate the predictions "manually" using `model.matrix(cyl ~ gear, mtcars_test) %*% coef(model)`. You'd also need to apply the inverse of the link function to get predictions on the response scale. – Roland May 24 '18 at 08:32
  • And of course you have the additional issue that your test data contains factor levels the model hasn't been trained on. – Roland May 24 '18 at 08:33
  • @Roland: thank you much for the input, I appreciate it. Just to exhaust this further, are there no way where one can modify the speedglm-object to act as an glm-object? – HeyJane May 24 '18 at 08:56
  • @Roland: model.matrix(cyl ~ gear, mtcars_test) %*% coef(model) does not seem to work for me – HeyJane May 24 '18 at 09:02
  • Of course it doesn't work because of the issue explained in my second comment. And how difficult is it to understand that you can't use methods on an object that is missing components the method needs? – Roland May 24 '18 at 09:14
  • @Roland: sorry for bothering you, I hope the agression shining through your comment did not ruin your day. model.matrix(cyl ~ gear, mtcars_train) %*% coef(model) does not work either, I just mistyped. And my question was just about modifying a glmspeed object to act like a glm-object, not regarding the issue of predicting – HeyJane May 24 '18 at 10:23
  • `model.matrix(cyl ~ gear, droplevels(mtcars_train)) %*% coef(model) ` and I've answered the other question twice already. You can of course simply do `class(model) <- "glm"` but most methods will simply not work, including the predict method. – Roland May 24 '18 at 10:26

0 Answers0