如何保存使用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!
答案 0 :(得分: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)