我有一个xgboost的模型文件,是在R中使用xgboost::save()
生成的。现在,我想要在Python中加载并使用它。
由于Python实现无法从字节串中加载模型,这在标准Python XGBoost库中似乎不可能(编辑:如此Github线程所述,这是一个错误).
该线程中的评论提供了一种解决方法,使用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)
xgboost::save("/path/to/file")
保存了你的模型,那么该模型将以xgboost-internal binary format
格式保存,可以通过Python的xgboost
包进行读取。
首先,在Python中安装:
pip install xgboost
conda install -c conda-forge xgboost
import xgboost
from xgboost import Booster
booster = Booster()
model = booster.load_model("/path/to/file")
在R中其他的保存方式(saveRDS()
)无法轻松地转移到Python。
str(xgboost.model)
的输出是什么?你能发布在R中生成这种模型的代码吗? - Gwang-Jin Kim