Skip to content

No supported methods for JSON serialization of trained XGBoost model without using disk #7158

Description

@amohar2

XGBoost's Learning API for Python provides the following ways to save/load the model:

  1. save_config/load_config: this will save/load the internal Booster configuration parameters as JSON. However, it seems that save_config does not save all the required information to load Booster object from scratch. For example, the following code:

`import xgboost
from sklearn.datasets import make_classification

x, y = make_classification(50, 21, 6, n_classes=2)
xtest, ytest = make_classification(10, 21, 6, n_classes=2)
param = {
'eta': 0.3,
'max_depth': 3,
'objective': 'multi:softprob',
'num_class': 3}
dtrain = xgboost.DMatrix(x, label=y)
dtest = xgboost.DMatrix(xtest)
booster = xgboost.train(param, dtrain)
booster.predict(dtest)

saved_config = booster.save_config()

booster = xgboost.Booster()
booster.load_config(saved_config)
booster.predict(dtest)`

will produce the following error:
Traceback (most recent call last):
File "test_xgb.py", line 23, in
booster.predict(dtest)
File "python3.8/site-packages/xgboost/core.py", line 1749, in predict
_check_call(
File "python3.8/site-packages/xgboost/core.py", line 210, in _check_call
raise XGBoostError(py_str(LIB.XGBGetLastError()))
xgboost.core.XGBoostError: [23:39:08] xgboost/src/learner.cc:602: Check failed: mparam
.num_feature != 0 (0 vs. 0) : 0 feature is supplied. Are you using raw Booster interface?

  1. save_model/load_model: using these two functions, we can save the model from disk and load it back successfully. However, in my particular application, I want to avoid writing the saved model to disk, and save_model() does not provide this option.

  2. save_raw/load_model: using save_raw(), we can save the model into a buffer in memory, and load it back with load_model(). It seems that save_raw() always returns a bytes type object that will be used in load_model(). However, similar to pickle, this will create security issues, since malicious code can be executed using bytes type objects.

Are there any other serialize/deserialize functions in XGBoost Learning/Scikit-Learn APIs that address the following requirements:

  1. save the model as string or JSON in memory (not bytes/bytearray)
  2. can be used to initialize the XGBoost model at a later time

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions