R 中的一些对象实际上是指向较低级别(不确定这是否是正确的术语)结构的指针,这些结构需要专门的函数来保存到磁盘。例如,saveRDS
不足以保留lightgbm
提升树:
## Create a lightgbm booster
library(lightgbm)
data(agaricus.train, package = "lightgbm")
train = agaricus.train
bst = lightgbm(data = train$data,label = train$label,
nrounds = 1, objective = "binary")
## but suppose bst is only one part of a bigger analysis
results = list(bst = bst, metadata = 'other stuff')
## then it would be nice if this IO cycle worked, but the last line crashes R
# saveRDS(results, file = 'so_post_temp')
# rm(results)
# rm(bst)
# lgb.unloader(wipe = TRUE)
# results = readRDS('so_post_temp')
# predict(results$bst, train$data)
标准解决方案并不可怕,但足以惹恼我。它需要使用单独的 lightgbm 特定保护程序,并为我要保存的任何分析创建单独的“伴侣”文件:
results = list(lgbpath = 'bst.lightgbm', metadata = 'other stuff')
saveRDS(results, file = 'so_post_temp')
lgb.save(bst, file = 'bst.lightgbm')
# destruct:
rm(results)
rm(bst)
lgb.unloader(wipe = TRUE)
# reconstruct:
results = readRDS('so_post_temp')
bst = lgb.load(results$lgbpath)
predict(bst, train$data)
有没有办法清理这个以某种方式将 R 对象和其他对象绑定到一个文件中?就像是
fake_pointer_to_disk = [points to some kind of R object instead]
fake_file_object = lgb.save(bst, file = fake_pointer_to_disk)
results = list(bst = fake_file_object, metadata = 'other stuff')
# later loaded as
bst = lgb.load(results$bst)