Sub topic 17
Saving and loading models
This chapter assumes you can train an XGBClassifier with the scikit-learn API and know what a Booster is. You will learn how to save a trained model, load it back, and avoid the usual problems when you move a model between machines or library versions.
Why the format matters
A trained XGBoost model is a list of trees plus a few settings, such as the objective and the base score. Saving it means writing those to disk so that a later process can predict without retraining.
XGBoost supports two kinds of persistence:
- Model serialization with
save_modelandload_model. This writes a portable file in JSON or the older UBJSON and binary formats. The file is meant to stay readable across XGBoost versions. - Python pickling with
pickleorjoblib. This stores the whole Python object. It depends on the XGBoost and Python versions and can run arbitrary code when loaded.
Prefer save_model. The format is chosen by the file extension: .json writes JSON, .ubj writes UBJSON (a compact binary form of JSON), and .deprecated writes the legacy binary format.
Save and load with the scikit-learn API
The example below trains on imbalanced data, saves the model to JSON, and loads it into a fresh estimator.
from sklearn.datasets import make_classification
from sklearn.model_selection import train_test_split
from xgboost import XGBClassifier
X, y = make_classification(
n_samples=5000, n_features=20, weights=[0.95, 0.05], random_state=0
)
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.2, stratify=y, random_state=0
)
spw = (y_train == 0).sum() / (y_train == 1).sum()
model = XGBClassifier(
n_estimators=200, learning_rate=0.1, max_depth=4,
scale_pos_weight=spw, eval_metric="aucpr",
)
model.fit(X_train, y_train)
model.save_model("model.json")
loaded = XGBClassifier()
loaded.load_model("model.json")
print(loaded.predict_proba(X_test)[:3])The loaded model gives the same probabilities as the original. You can check this with numpy.allclose(model.predict_proba(X_test), loaded.predict_proba(X_test)).
Save a native Booster
A Booster has the same two methods. Booster.load_model works on an existing object, so create an empty Booster first.
import xgboost as xgb
booster = model.get_booster()
booster.save_model("booster.json")
restored = xgb.Booster()
restored.load_model("booster.json")You can move a file between the two APIs. A file written by XGBClassifier.save_model can be read by Booster.load_model, and the reverse works as well.
Common errors
| Problem | Cause | Fix |
|---|---|---|
| Wrong results after loading | Features passed in a different order or with different names | Keep the same column order as in training |
| Warning about a missing parameter | The file was written by a different XGBoost version | Load with a recent version, then re-save |
| Custom training settings are gone | The file stores the model, not every scikit-learn setting | Save your hyperparameters separately if you need to retrain |
| Unsafe load | Unpickling untrusted files | Load only files you trust, and prefer `load_model` |
Exercise
You trained an XGBClassifier on one server and need to use it on another server that may run a newer XGBoost version. Which saving method should you choose, and why?
Show answer
Use save_model with a .json (or .ubj) file. The format is designed to stay readable across XGBoost versions. Pickle depends on matching Python and XGBoost versions and can execute code when loaded.
Exercise
After loading a saved model, predictions differ from the original model's predictions. Name one likely cause that does not involve the model file itself.
Show answer
The input features are in a different column order, or have different names, than during training. Make sure the prediction data has the same columns in the same order.