python - 在Python中加载xgboost模型,该模型由R中的 `xgboost::save()`保存

标签 python r xgboost

我有一个 xgboost .model 文件,它是在 R 中使用 xgboost::save() 生成的。现在,我想加载该文件并在 python 中使用它。

最佳答案

这似乎是不可能的(编辑:在标准 python xgboost 库中),因为 python 实现无法从字节串加载模型,这是一个根据 this github thread 的错误

该线程中的注释提供了使用 xgboost.core 库的解决方法函数:

import ctypes
import xgboost
import xgboost.core

def xgb_load_model(buf):
    if isinstance(buf, str):
        buf = buf.encode()
    bst = xgboost.core.Booster()
    n = len(buf)
    length = xgboost.core.c_bst_ulong(n)
    ptr = (ctypes.c_char * n).from_buffer_copy(buf)
    xgboost.core._check_call(
        xgboost.core._LIB.XGBoosterLoadModelFromBuffer(bst.handle, ptr, length)
    )  
    return bst

如果您在二进制文件中读取类似以下内容:

with open('xgb_model.model','rb') as f:
    raw = f.read()

您应该能够通过以下方式从字节串加载:

model = xgb_load_model(raw)

关于python - 在Python中加载xgboost模型,该模型由R中的 `xgboost::save()`保存,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56506019/

相关文章:

python - 我对使用 Xgboost 的 hyperopt 包的 fmin() 函数有很大的兴趣

python - 模块 'xgboost' 没有属性 'DMatrix'

python - 以特殊格式打印当前 UTC 日期时间

Python 多线程

r - TM 包中删除 URLS 的 gsub 函数不会删除整个字符串

r - 如何以编程方式创建 R 函数?

python - 获取任务来自的队列

Python:变量、继承和默认参数

r - 根据名称获取变量的平均值

r - 为什么 XGB 模型没有在验证数据集上提供输出,但更适合训练