如何解决R 目标与 H2O
我使用 targets
作为带有 H2O
的 ML 项目的流水线工具。
在这里使用 H2O 的主要独特之处在于它创建了一个新的“集群”(基本上是一个新的本地进程/服务器,据我所知,它通过 Rest API 进行通信)。
我遇到的问题有两方面。
- 如何以智能方式停止/操作目标框架内的集群
- 如何在目标框架内保存和加载数据/模型
MWE
我想出的最小工作示例如下所示(即 _targets.R
文件):
library(targets)
library(h2o)
# start h20 cluster once _targets.R gets evaluated
h2o.init(nthreads = 2,max_mem_size = "2G",port = 54322,name = "TESTCLUSTER")
create_dataset_h2o <- function() {
# connect to the h2o cluster
h2o.init(ip = "localhost",name = "TESTCLUSTER",startH2O = FALSE)
# convert the data to h2o dataframe
as.h2o(iris)
}
train_model <- function(hex_data) {
# connect to the h2o cluster
h2o.init(ip = "localhost",startH2O = FALSE)
h2o.randomForest(x = c("Sepal.Length","Sepal.Width","Petal.Length","Petal.Width"),y = c("Species"),training_frame = hex_data,model_id = "our.rf",seed = 1234)
}
predict_model <- function(model,hex_data) {
# connect to the h2o cluster
h2o.init(ip = "localhost",startH2O = FALSE)
h2o.predict(model,newdata = hex_data)
}
list(
tar_target(data,create_dataset_h2o()),tar_target(model,train_model(data),format = "qs"),tar_target(predict,predict_model(model,data),format = "qs")
)
这有点奏效,但面临着我在上下两方面的两个问题......
广告 1 - 停止集群
通常我会在脚本的末尾输出一个 h2o::h2o.shutdown(prompt = FALSE)
,但这在这种情况下不起作用。
或者,我想出了一个总是运行的新目标。
# in _targets.R in the final list
tar_target(END,h2o.shutdown(prompt = FALSE),cue = tar_cue(mode = "always"))
这在我运行 tar_make()
时有效,但在我使用 tar_visnetwork()
时无效。
另一种选择是使用。
# after the h2o.init(...) call inside _targets.R
on.exit(h2o.shutdown(prompt = FALSE),add = TRUE)
我想出的另一种选择是在目标之外处理服务器并且只连接到它。但我觉得这可能会破坏目标工作流程...
您对如何处理这个问题还有其他想法吗?
广告 2 - 保存数据集和模型
MWE 中的代码没有以正确的格式 (model
) 保存目标 predict
和 format = "qs"
的数据。有时(我认为当集群重新启动时),数据“无效”并且 h2o 会引发错误。 R 会话中 h2o 格式的数据是指向 h2o 数据帧的指针(另见 docs)。
对于类似将模型存储在 R 之外的 keras,有选项 format = "keras"
,它在幕后调用 keras::save_model_hdf5()
。同样,H2O 需要 h2o::h2o.exportFile()
和 h2o::h2o.importFile()
用于数据集,h2o::h2o.saveModel()
和 h2o::h2o.loadModel()
用于模型(另见 docs)。
有没有办法为 tar_targets
创建其他格式,或者我是否需要将数据写入文件并返回文件?这样做的缺点是,如果我没记错的话,这个文件在 _targets
文件夹系统之外。
解决方法
广告 1
我建议在单独的脚本中处理管道外的 H2O 集群。这样,tar_visnetwork()
就不会启动或停止集群,您可以更清晰地将软件工程与数据分析分开。
# run_pipeline.R
start_h2o_cluster(port = ...)
on.exit(stop_h2o_cluster(port = ...))
targets::tar_make_clustermq(workers = 4)
广告 2
听起来 H2O 对象是 not exportable。目前,您需要手动保存这些文件、确定路径并在 format = "file"
中写入 tar_target()
。我愿意考虑基于 H20 的格式。 h2o.exportFile()
、h2o.importFile()
、h2o::h2o.saveModel()
和h2o::h2o.loadModel()
是否以某种方式覆盖了所有对象,或者是否有更多种类的具有不同序列化功能的对象? h2o
是否具有在内存中执行此(非)序列化的实用程序,例如 serialize_model()
中的 unserialize_model()
/keras
?
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。