有没有一种方法可以导出和导入模型,而不是每次会话都重新运行它们?
Is there a way to export and import models rather than re-running them every session?
我必须 运行 许多计算密集型模型才能工作(例如,泊松族 glmers 有很多嵌套在其他随机效应中的随机效应),根据它们做出预测,然后将它们绘制成图表。有时我的经理希望我对预测或图表进行更改,但模型有时需要几个小时才能完成 运行。有没有一种方法可以通过导出和导入模型对象来节省时间,而不必每次都在脚本中重新运行它们?
您可以使用 saveRDS(object, filename)
保存任何对象,然后使用 readRDS(filename)
将其读回 R。参见 ?saveRDS
。
counts <- c(18,17,15,20,10,20,25,13,12)
outcome <- gl(3,1,9)
treatment <- gl(3,3)
d.AD <- data.frame(treatment, outcome, counts)
glm.D93 <- glm(counts ~ outcome + treatment, family = poisson())
保存模型对象
saveRDS(glm.D93, file="glm.rds")
rm(glm.D93)
检索模型对象
glm.D93 <- readRDS("glm.rds")
anova(glm.D93)
# Analysis of Deviance Table
# Model: poisson, link: log
# Response: counts
# Terms added sequentially (first to last)
# Df Deviance Resid. Df Resid. Dev
# NULL 8 10.5814
# outcome 2 5.4523 6 5.1291
# treatment 2 0.0000 4 5.1291
我必须 运行 许多计算密集型模型才能工作(例如,泊松族 glmers 有很多嵌套在其他随机效应中的随机效应),根据它们做出预测,然后将它们绘制成图表。有时我的经理希望我对预测或图表进行更改,但模型有时需要几个小时才能完成 运行。有没有一种方法可以通过导出和导入模型对象来节省时间,而不必每次都在脚本中重新运行它们?
您可以使用 saveRDS(object, filename)
保存任何对象,然后使用 readRDS(filename)
将其读回 R。参见 ?saveRDS
。
counts <- c(18,17,15,20,10,20,25,13,12)
outcome <- gl(3,1,9)
treatment <- gl(3,3)
d.AD <- data.frame(treatment, outcome, counts)
glm.D93 <- glm(counts ~ outcome + treatment, family = poisson())
保存模型对象
saveRDS(glm.D93, file="glm.rds")
rm(glm.D93)
检索模型对象
glm.D93 <- readRDS("glm.rds")
anova(glm.D93)
# Analysis of Deviance Table
# Model: poisson, link: log
# Response: counts
# Terms added sequentially (first to last)
# Df Deviance Resid. Df Resid. Dev
# NULL 8 10.5814
# outcome 2 5.4523 6 5.1291
# treatment 2 0.0000 4 5.1291