How to save xgboost model as a json of jsons?

Viewed 1504

After training an xgboost model, I would like to save it and some other custom fields as a json object as below. The purpose being so I can load the json object later, use the model object to make predictions as well as inspecting the other custom fields.

model = xgb.train(params=tree_params, dtrain=data)
my_model_dict = {
    "model": ...<json serializable model object>...,  # need help here
    "features": model.feature_names,
    "tree_params": tree_params,
    ...
}
json.dumps(my_model_dict, file_path)

my_model_dict = json.load(file_path)
model = my_model_dict["model"]
predictions = model.predict(new_data)

Is it possible to convert an xgboost model object into an object that is json serializable and that can then be loaded to make standard xgboost predictions?

I appreciate I can save the raw model seperately as a json using

model.save_model("my_model.json")
model = xgb.Booster("my_model.json")
model.predict(new_data)

but really what I would like to do is create a dictionary containing the model along with other custom fields that can be saved as a json, then loaded to make predictions.

0 Answers
Related