如何正确保存mlr3 lightgbm模型?

How to save mlr3 lightgbm model correctly?

我有以下代码。保存经过训练的模型时遇到错误。 只有当我使用 lightgbm.

时才会出错
library(mlr3)
library(mlr3pipelines)
library(mlr3extralearners)

data = tsk("german_credit")$data()
data = data[, c("credit_risk", "amount", "purpose", "age")]
task = TaskClassif$new("boston", backend = data, target = "credit_risk")

g = po("imputemedian") %>>%
  po("imputeoor") %>>%
  po("fixfactors") %>>%
  po("encodeimpact") %>>% 
  lrn("classif.lightgbm")

gl = GraphLearner$new(g)

gl$train(task)

# predict 
newdata <- data[1,]
gl$predict_newdata(newdata) 
saveRDS(gl, "gl.rds")
# read model from disk ----------------
gl <- readRDS("gl.rds")
newdata <- data[1,]

# error when predict ------------------
gl$predict_newdata(newdata)

lightgbmsave and read 模型使用特殊功能。您必须在保存之前提取模型,并在加载后将其添加到图学习器中。但是,这对于基准测试可能不切实际。我们会调查的。

library(mlr3)
library(mlr3pipelines)
library(mlr3extralearners)
library(lightgbm)

data = tsk("german_credit")$data()
data = data[, c("credit_risk", "amount", "purpose", "age")]
task = TaskClassif$new("boston", backend = data, target = "credit_risk")

g = po("imputemedian") %>>%
  po("imputeoor") %>>%
  po("fixfactors") %>>%
  po("encodeimpact") %>>% 
  lrn("classif.lightgbm")

gl = GraphLearner$new(g)

gl$train(task)

# save model
saveRDS.lgb.Booster(gl$model$classif.lightgbm$model, "model.rda")

# save graph learner
saveRDS(gl, "gl.rda")

# load model
model = readRDS.lgb.Booster("model.rda")

# load graph learner
gl = readRDS("gl.rda")

# add model to graph learner
gl$state$model$classif.lightgbm$model = model

# predict
newdata <- data[1,]
gl$predict_newdata(newdata)