How to save a glmnet model to a file in R?

2k views Asked by At

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!

2

There are 2 answers

0
alittleboy On BEST ANSWER

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 use load(YourFile.RData) to load the object(s) into session.

0
Peter On
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")