How to save a glmnet model to a file in R?
Asked Answered
E

2

5

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!

Ecbatana answered 9/12, 2013 at 3:26 Comment(0)
C
7

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.

Comfortable answered 9/12, 2013 at 3:55 Comment(0)
P
1
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")
Punk answered 16/11, 2020 at 9:7 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.