Load a xgboost model in python which was saved by `xgboost::save()` in R

Viewed 10138

I have a xgboost .model file which was generated using xgboost::save() in R. Now, I want to load this and use it in python.

2 Answers

This does not appear to be possible (edit: in the standard python xgboost libary) due to an inability of the python implementation to load models from bytestring, a bug according to this github thread

A comment in that thread provides a workaround function, using the xgboost.core library:

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

If you read in your binary file with something like:

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

you should be able to load from the bytestring with:

model = xgb_load_model(raw)

If you saved your model using xgboost::save("/path/to/file") in R, then the model is saved in xbgoost-internal binary format, which can be read-in by Python's xgboost package.

First, install in Python by:

pip install xgboost

or if you are a conda user like me:

conda install -c conda-forge xgboost

Then, load into Python by:

import xgboost
from xgboost import Booster

booster = Booster()
model = booster.load_model("/path/to/file")

Other ways of saving in R (saveRDS()) wouldn't allow easy transfer into Python.

Related