问题
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
回答1:
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")
回答2:
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.
回答3:
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.
来源:https://stackoverflow.com/questions/20346633/prediction-using-saved-model-object