Prediction using saved model object - r

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

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")

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.

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.

Related

How to save a ranger model in mlr3 without data?

I have created a ranger model using mlr3 library. I saved this model to my machine using following command. The created file is huge in size. The saved file also has the data along with the model. Is there a way to only save the model without the data?
learner_ranger = lrn("classif.ranger", predict_type = "prob", predict_sets = c("train", "test"), importance = "impurity", num.threads = 8)
learner_ranger$train(train_task])
save(learner_ranger, file = "model.rda")
When I try to load this saved model it does not load the model correctly.
learner_ranger = load("model.rda")
str(learner_ranger)
Error in str(learner_ranger) : object 'learner_ranger' not found
To reduce the file size and save only the model, I have tried following but I am getting an error
save(learner_ranger$model, file = "model.rda")
The error I am getting is -
Error in save(learner_ranger$model, file = "model.rda") :
object ‘learner_randomF$model’ not found
After some research found that there are two ways to save and load the model in R:
using save(), load(): When we use save(), we will have to load it using the same name.
using saveRDS(), loadRDS(): saveRDS() does not save the model name and we have the flexibility to load the model in any other name. But saveRDS() can only save one object at a time as it is a lower-level function.
Most people prefer saveRDS() over save() as it serializes the object.
I am still looking for ways to save the model without data.

Trouble with pairs() function in nlme

I am having trouble getting the pairs() function to work in nlme. Take this example from Pinhiero and Bates Mixed-Effects Models in S and S-Plus.
The model itself runs just fine
fm1Theo.lis <- nlsList(conc ~ SSfol(Dose, Time, lKe, lKa, lCl), data = Theoph)
But the pairs plot...
pairs(fm1Theo.lis, id = 0.1)
...returns this error
Error in as.data.frame.default(x) :
cannot coerce class "c("nlsList", "lmList")" to a data.frame
I also tried
pairs(fm1Theo.lis, ~ ranef(., level = 2), id = 0.1)
But get the same error. Any ideas?
Here's how one may think in this case. The error
Error in as.data.frame.default(x) :
cannot coerce class ‘c("nlsList", "lmList")’ to a data.frame
says that some object of class c("nlsList", "lmList") is being coerced to a data frame. Now since fm1Theo.lis is the result of using nlsList, it seems that the object in the error is indeed nlsList. That means that pairs does not know what to do with objects of such class. To confirm this, we can run
pairs.default(fm1Theo.lis, id = 0.1)
which is what is going to happen when no specific method for fm1Theo.lis is found. Indeed the error is the same. In one way or another confirming that nlsList and comes from nlme, it becomes clear that the issue is with loading the nlme package. Loading it or restarting the session then is almost surely going to help.

Save the Deep learning model by R language

I have established a deep learning model with the h2o package of the R software. I gained a model with good presence and I wanna to save it. However, I tried all kinds of methods but failed. The code "save()" and "save.image()" are provided in the base package of R software. I used the "save()" function to conserve my model. But when I want to use the built model to run new data, it is said that the "model" object is not found in the function. I am really confused about this problem for a few days. If you have any good ideas, just tell me. Thanks for your reading~
load("F:/R/Rstudy/myfile") ##download the saved file
library(h2o)
h2o.init()
Te <- read.csv("F:/Rdata/Test.csv") ## import testing data
Te <- as.h2o(Te)
Te[,2] <- as.factor(Te[,2])
perf <- h2o.performance(model, Te) ## test model
ERROR: Unexpected HTTP Status code: 404 Not Found (url = http://localhost:54321/3/ModelMetrics/models/DeepLearning_model_R_1533035975237_1/frames/RTMP_sid_8185_2)
ERROR MESSAGE:
Object 'DeepLearning_model_R_1533035975237_1' not found in function: predict for argument: model
You can use the below to save and retrieve the model.
build the model
model <- h2o.deeplearning(params)
save the model
model_path <- h2o.saveModel(object=model, path=getwd(), force=TRUE)
print(model_path)
/tmp/mymodel/DeepLearning_model_R_1441838096933
load the model
saved_model <- h2o.loadModel(model_path)
Reference - http://docs.h2o.ai/h2o/latest-stable/h2o-docs/save-and-load-model.html
Hope this helps,
ND

fpgrowth error in R

I am trying to fit a fpgrowth model on a in-built data set called Adult. While fitting a model, I was getting an error as shown below.
Error in .jcall(jPruning, "[[Ljava/lang/String;", "fpgrowth", support, :
method fpgrowth with signature (DDI)[[Ljava/lang/String; not found
I used the below R code to fit fpgrowth model.
library(rCBA)
data("Adult")
Adult<-as(Adult,"transactions")
rules = rCBA::fpgrowth(Adult, support=0.001, confidence=0.5, maxLength=2)
What's wrong with the above code?
Thanks in advance.
you must specify your "class" or consequent
rules = rCBA::fpgrowth(Adult, support=0.001, confidence=0.5, maxLength=2, consequent="Species")
Try with This:
https://rdrr.io/cran/rCBA/src/R/fpgrowth.R

Load classification tree model on new raster data set

I am working with a classification tree model that allows me to classify raster images (to create maps). I would like to reapply this classification tree to a new raster dataset, in another script.
I tried to save the model as .rda or .RData file but I have the same problem it's impossible to predict the model on the new dataset.
no applicable method for 'predict' applied to an object of class "character"
I'm pretty sure the problem is due to the save function of the model since it does not appear entirely:
summary(model)
# Length Class Mode
# 1 character character
I'm saving my model with this code :
save(cuttreedown.training, file =("Artmac.rda")
and load it with :
model <- load("Artmac.rda")
And this is my predict function where satImage is my raster file (the function is working well on another script) :
predict(satImage, model, filename="test.tif", progress='text', datatype='INT1U', type='prob', overwrite=TRUE)
I just want to apply my model on a new raster dataset as it is done in the training script.
You can use saveRDS/loadRDS for such a task. Here is a full example:
library(rpart)
data(iris)
fit <- rpart(Species~., data = iris)
saveRDS(fit, "fit.rds")
load_fit <- readRDS("fit.rds")
all.equal(predict(load_fit, iris),
predict(fit, iris))
#output
TRUE
simply save and load the model without an extension. Also, don't create a new object when loading, it will automatically populate the model object into the environment. Try:
save(cuttreedown.training, file="Artmac")
load("Artmac")
summary(Artmac)

Resources