When I am using R, how can I save a model built by glmnet to a file, and then read it from the file so as to use it to predict?
Is it also the same if I use cv.glmnet to build the model?
Thanks!
library(glmnet)
library(ISLR)
# Data and model
auto = ISLR::Auto
mod = cv.glmnet(as.matrix(auto[1:300,2:6]), as.matrix(auto[1:300,1]), type.measure = "mse", nfolds = 5)
predict(mod, newx = as.matrix(auto[300:392,2:6]), s = "lambda.min")
# Save model
save(mod, file="D:/mymodel.RData")
rm(mod)
# Reload model
load("D:/mymodel.RData")
predict(mod, newx = as.matrix(auto[300:392,2:6]), s = "lambda.min")
Maybe I misunderstand your point, but it is always feasible to use the
save
function to save your R object in the.RData
file. Next time, you simply useload(YourFile.RData)
to load the object(s) into session.