2

如何保存使用 mlr 包训练的 h2o 模型并将其加载到新会话中以预测新数据集的目标变量?在下面的示例中,我使用 save 和 h2o.saveModel 进行了尝试,但它会引发错误。

library(mlr)
a <- data.frame(y=factor(c(1,1,1,1,1,1,1,1,0,0,1,0)), 
                x1=rep(c("a","b", "c"), times=c(6,3,3)))
aTask <- makeClassifTask(data = a, target = "y", positive="1")
h2oLearner <- makeLearner("classif.h2o.deeplearning")
model <- train(h2oLearner, aTask)
# save mlr and h2o model separately:
save(file="saveh2omodel.rdata", list=c("model"))
h2o.saveModel(getLearnerModel(model), path="h2o_model")

# shutdown h2o and close R and open new session
h2o.shutdown()

library(mlr)
library(h2o)
h2o.init()
h2o.loadModel("h2o_model")
load(file="saveh2omodel.rdata")
#ERROR: Unexpected HTTP Status code: 412 Precondition Failed (url = http://localhost:54321/99/Models.bin/)
# Error in .h2o.doSafeREST(h2oRestApiVersion = h2oRestApiVersion, urlSuffix = page,  :                             
#  ERROR MESSAGE:
#  Illegal argument: dir of function: importModel: h2o_model

b <- data.frame(x1=rep(c("a","b", "c"), times=c(3,5,4)))
pred <- predict(model, newdata=b) 
# only works if h2o wasn't shut down!
4

1 回答 1

6

您使用h2o.loadModel不正确(与 无关mlr)。请参阅帮助中的示例用法h2o-h2o.saveModel返回您需要提供的完整路径h2o.loadModel。完整的工作示例:

library(mlr)
library(h2o)
a <- data.frame(y=factor(c(1,1,1,1,1,1,1,1,0,0,1,0)), 
                x1=rep(c("a","b", "c"), times=c(6,3,3)))
aTask <- makeClassifTask(data = a, target = "y", positive="1")
h2oLearner <- makeLearner("classif.h2o.deeplearning")
model <- train(h2oLearner, aTask)
# save mlr and h2o model separately:
save(file="saveh2omodel.rdata", list=c("model"))
savedModel = h2o.saveModel(getLearnerModel(model), path="h2o_model")

# shutdown h2o and close R and open new session
h2o.shutdown()

library(mlr)
library(h2o)
h2o.init()
h2o.loadModel(savedModel)
load(file="saveh2omodel.rdata")
b <- data.frame(x1=rep(c("a","b", "c"), times=c(3,5,4)))
pred <- predict(model, newdata=b) 
于 2017-07-10T20:44:23.790 回答