通过 save
或 saveRDS
等函数反序列化 LightGBM 模型对象后,其底层的 C++ 对象将为空白,需要恢复才能使用。调用 predict
等函数时,此类对象会自动恢复,但可以使用此函数提前强制恢复它。请注意,对象将在原位被修改。
4.0.0 版本新增
lgb.restore_handle(model)
lgb.Booster
(与作为输入传入的 `model` 对象相同,不可见地)。
请注意,通过此函数不会恢复快速单行预测配置。如果您希望使用通过此方式加载的 lgb.Booster
进行快速单行预测,请在加载的 lgb.Booster
对象上调用 lgb.configure_fast_predict。
# \donttest{
library(lightgbm)
data("agaricus.train")
model <- lightgbm(
agaricus.train$data
, agaricus.train$label
, params = list(objective = "binary")
, nrounds = 5L
, verbose = 0
, num_threads = 2L
)
#> [LightGBM] [Warning] No further splits with positive gain, best gain: -inf
#> [LightGBM] [Warning] No further splits with positive gain, best gain: -inf
#> [LightGBM] [Warning] No further splits with positive gain, best gain: -inf
#> [LightGBM] [Warning] No further splits with positive gain, best gain: -inf
#> [LightGBM] [Warning] No further splits with positive gain, best gain: -inf
fname <- tempfile(fileext="rds")
saveRDS(model, fname)
model_new <- readRDS(fname)
model_new$check_null_handle()
#> [1] TRUE
lgb.restore_handle(model_new)
model_new$check_null_handle()
#> [1] FALSE
# }