Prediction using saved model object

2019-05-17 20:27发布

I am trying to use predict function in R using a model saved earlier. The model was created and saved using the following code:

    lrModel1 <- glm(response ~ .,data = modelData,family = binomial,model = TRUE)
    save(lrModel1,file = "lrModel100.rda")

When I load the model for later use as follows and try to use the predict function on it as follows:

    bar <- load("lrModel100.rda")
    predicted <- predict(bar,validationData,type = "response")

I get the following error:

    Error in UseMethod("predict") : 
            no applicable method for 'predict' applied to an object of class "character"

Is there a way to get the model object name from the saved RDA file and use it for prediction?

Thank you.

Ravi

标签: r predict
3条回答
看我几分像从前
2楼-- · 2019-05-17 20:58

As @droopy told you the model's name doesn't change if you save and load. You can use get to use the model:

predicted <- predict(get(bar),validationData,type = "response")
查看更多
在下西门庆
3楼-- · 2019-05-17 21:13

I have same problem before.

I used caret to build model, and save the model as a rds file.(saveRDS)

When I readRDS my file, and use this model to predict, I encountered this problem.

After I use "library(caret)", my problem is solved.

So I think if you save your model, and re-open your model to predict, you have to reload the package you used for building model.

查看更多
Fickle 薄情
4楼-- · 2019-05-17 21:16

If you have saved the model earlier it may throw this error. Reload the library(glmnet) and make sure that number of variables in X & Y are same.

查看更多
登录 后发表回答