【问题标题】:Saving space when saving a fitted gam object (mgcv::gam and scam::scam)保存适合的 gam 对象时节省空间(mgcv::gam 和scam::scam)
【发布时间】:2019-01-10 00:38:28
【问题描述】:

我在大型数据集上估计一个非常简单的模型。公式看起来像

 scam::scam(formula = ratio ~ s(rate,bs="mpi"))

这些模型随后用于为新数据生成预测。我不关心模型的其他任何事情。

我的问题是返回的对象很大(几 GB),这往往会导致下游出现问题。

我相信这是因为骗局和游戏保存了数百万条记录中的每一条的拟合值。

有没有办法只保存一个小对象,其中包含预测新数据所需的最小值?这不应大于几千字节。

非常感谢!

edit1:这是一个可重现的示例,以显示我对 Gavin 答案的理解:

library(mgcv)
data(iris)
library(tidyverse)
mydb <- iris %>% filter(Species == "setosa")

dim(mydb) # 50 records
model <-  mgcv::gam(formula = Sepal.Length ~ s(Sepal.Width,bs="cs"), 
                     data  = mydb)

print(object.size(model), units = "KB") # 78 KB

distinct_mydb <- mydb %>% distinct(Sepal.Width) # 16 distinct values for the independent variables
Xp <- predict(model, newdata= distinct_mydb, type = "lpmatrix")
coefs <- coef(model)
dim(Xp) # 16 records and 10 columns (one for each of the 10 knots of the spline?)
preds1 <- Xp %*% coefs %>% t()  
preds2 <- predict(model, newdata= distinct_mydb)  # preds 1 and preds2 are identical

print(object.size(Xp), units = "KB")   # 3.4 Kb
print(object.size(coefs), units = "KB") # 1.1 Kb

在这个解决方案中,我将保存“Xp”(3.4 Kb)和“coefs”(1.1Kb)总共 4.5 Kb,而不是保存占用 78 Kb 的“模型”

我不确定如何在下周使用 Xp 和 coefs 来预测花的 Sepal.Length,而 Sepal.Width 为 2.5?

edit2 :答案仅仅是生成所有可能的 Sepal.Width 的网格(四舍五入到小数点),然后将这个表与任何未来的数据一起 left_join 吗?

fake_db <- data.frame(Sepal.Width = seq(0,max(mydb$Sepal.Width), by = 0.1))
fake_db$predicted_Sepal.Length = predict(model, newdata =  fake_db)
print(object.size(fake_db), units = "KB") # 4.3 Kb

【问题讨论】:

    标签: r gam mgcv


    【解决方案1】:

    查看?mgav:::predict.gam 和参数type 的信息,尤其是"lpmatrix"

    例如你只需要系数向量和来自

    的输出
    predict(model, newdata, type = "lpmatrix")`
    

    其中newdata 是原始数据的一个小得多的子集,但涵盖了协变量的范围。

    此选项"lpmatrix" 设计用于下游或 R 外部。一般的想法是给定 "lpmatrix"Xp 然后 Xp %*% coef(model) 给出拟合值。但由于您可以通过newdata 减小Xp 的大小,您可以减少预测所需对象的维度。

    【讨论】:

    • 我已经阅读了很多你对这个一般性问题的回答,但我认为我仍然遗漏了一些东西。它是否正确? xp &lt;- predict(original_model, newdata = original_data, type = 'lpmatrix') coefs &lt;- coef(model) fitted_values &lt;- xp %*% coefs %&gt;% t() 使用这种模式,我将如何引入一批新的数据进行评分?我是为每个新批次生成一个新的 lpmatrix,还是有一个与原始训练数据相关联的 lpmatrix,可以存储并应用于每个后续批次的数据?
    • 等等,我想我明白了。对于您使用predict() 生成的每批新数据Xp,然后将其乘以coefs 以获得分数。
    猜你喜欢
    • 2016-01-07
    • 2020-03-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多