我有以下情况:
我有一些数据并在其上训练一些线性模型(可能带有一些交互项)。我保存了这个模型的系数,所以R以外的其他程序也可以使用它。
几周后,现在有办法仅从系数中读出我的模型吗?
我会想象类似的事情
df <- data.frame(x=1:5, y=c(1,6,8,11,9), z=c(1,2,5,10,3))
lmod <- lm(z~x+y+I(x^2), df)
predict(lmod, newdata = df)
co <- coefficients(lmod)
co
这给出了预测
-0.05 4.45 3.95 8.95 3.70
和系数
(Intercept) x y I(x^2)
8.8250 -12.9375 2.6250 1.4375
然后我会将
co
保存到文本文件或类似文件中。
fm <- formula(paste("z ~", paste(setdiff(names(co), "(Intercept)"), collapse = " + ")))
model <- lm(formula = fm, data = NULL)
model$coefficients <- co
predict(model, newdata = df)
并希望得到有意义的结果。但是这种方法行不通,有什么好的方法吗?
尝试
# saving the model
saveRDS(lmod, file = "model.rda")
#loading the model
model_old = readRDS("model.rda")
然后你会得到:
model_old
Call:
lm(formula = z ~ x + y + I(x^2), data = df)
Coefficients:
(Intercept) x y I(x^2)
8.825 -12.937 2.625 1.437