Sub topic 17
Saving and Loading Models
This chapter covers how to persist a trained XGBoost model, which formats exist, and how to avoid the failures that show up when a model is loaded months later in a different environment. It assumes you can train an XGBClassifier or a native Booster, and that you know the difference between a model's learned trees and its training-time settings.
What a saved model contains
A trained XGBoost model is a list of trees plus a small amount of metadata. The saved file holds the following:
- The tree structures and leaf values.
- The objective (for example
binary:logistic) and the base score. - Feature names and feature types, if you supplied them.
- Some attributes, such as the best iteration found by early stopping.
The file does not hold your preprocessing code, your train/validation split, or the Python environment. If you encoded categories or imputed values before training, you must save that pipeline separately.
Choosing a format
save_model picks the format from the file extension.
| Extension | Format | Use it when |
|---|---|---|
| `.json` | Text JSON | You want to inspect or diff the model, or share it across languages |
| `.ubj` | Universal Binary JSON | You want the same structure as JSON in a smaller, faster file |
| other or none | Depends on your XGBoost version | Avoid it, and name the extension explicitly |
Older XGBoost versions used a raw binary format that is now deprecated. Some versions use UBJSON when no extension is given. Because the default has changed between releases, always write the extension yourself.
Round trip with the scikit-learn API
The following example trains a classifier, saves it in both formats, reloads it, and checks that the predictions are unchanged. It also loads the same file into a native Booster.
import numpy as np
import xgboost as xgb
from sklearn.datasets import load_breast_cancer
from sklearn.model_selection import train_test_split
from xgboost import XGBClassifier
X, y = load_breast_cancer(return_X_y=True)
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.2, stratify=y, random_state=0
)
model = XGBClassifier(n_estimators=100, learning_rate=0.1, max_depth=3)
model.fit(X_train, y_train)
model.save_model("cancer.json")
model.save_model("cancer.ubj")
# Reload into a fresh wrapper
loaded = XGBClassifier()
loaded.load_model("cancer.json")
assert np.allclose(model.predict_proba(X_test), loaded.predict_proba(X_test))
# The same file also loads as a native Booster
booster = xgb.Booster()
booster.load_model("cancer.ubj")
p = booster.predict(xgb.DMatrix(X_test))
assert np.allclose(model.predict_proba(X_test)[:, 1], p)
print("round trip ok, xgboost", xgb.__version__)Note that Booster.predict returns the probability of the positive class only, while predict_proba returns both columns. That is why the second check slices column 1.
A scikit-learn wrapper and a native booster share the same file format. You can train with one API and serve with the other.
Saving a native Booster
The native API uses the same method names.
import xgboost as xgb
from sklearn.datasets import load_breast_cancer
data = load_breast_cancer()
dtrain = xgb.DMatrix(data.data, label=data.target,
feature_names=list(data.feature_names))
booster = xgb.train({"objective": "binary:logistic", "max_depth": 3},
dtrain, num_boost_round=50)
booster.save_model("native.json")
restored = xgb.Booster()
restored.load_model("native.json")
print(restored.feature_names[:3])Because the booster was trained with named features, the names are stored in the file and come back after loading. A model trained from a bare NumPy array has no names, so you cannot check column order at prediction time.
In-memory copies
save_raw returns the serialized model as a byte array, which is useful for storing a model in a database column, an object store, or a cache without touching the disk.
import xgboost as xgb
from sklearn.datasets import load_breast_cancer
data = load_breast_cancer()
dtrain = xgb.DMatrix(data.data, label=data.target)
booster = xgb.train({"objective": "binary:logistic"}, dtrain, num_boost_round=20)
raw = booster.save_raw(raw_format="json")
copy = xgb.Booster()
copy.load_model(bytearray(raw))
print(type(raw), copy.num_boosted_rounds())Pickle and joblib
You can pickle an XGBClassifier or a whole scikit-learn Pipeline that contains one. This is convenient, and it is the only simple way to keep a fitted preprocessing step and the model together. It has two costs.
- Pickle files are tied to the Python and library versions that wrote them. A file written by one XGBoost version may fail to load, or load incorrectly, in another.
- Unpickling untrusted data can run arbitrary code. Never load a pickle from a source you do not control.
The XGBoost documentation recommends save_model for anything you keep beyond a single session. A common pattern is to save the booster with save_model and to save the preprocessing separately in whatever format that library supports.
Record the context beside the file
A model file does not say which feature order it expects unless you gave names, and it does not record how you built the inputs. A small sidecar file removes most of the guesswork.
import json
import xgboost as xgb
metadata = {
"xgboost_version": xgb.__version__,
"features": [f"f{i}" for i in range(30)],
"objective": "binary:logistic",
"threshold": 0.5,
"trained_on": "2026-11-28",
}
with open("cancer.meta.json", "w") as f:
json.dump(metadata, f, indent=2)At load time, read the sidecar and compare xgboost_version with the installed version. Compare the feature list with the columns you are about to pass in.
Common errors
- Feature mismatch. Passing a DataFrame whose columns differ in name or order from training raises a
feature_names mismatcherror. Fix it by reordering columns to matchbooster.feature_names, not by disabling the check. - Unknown extension. Saving to
model.binormodel.modelmay produce a format you did not intend. Use.jsonor.ubj. - Training parameters lost. A loaded model keeps what it needs to predict, but a scikit-learn wrapper does not restore every constructor argument. If you plan to continue training, set your hyperparameters again explicitly.
- Newer file, older library. A model saved by a newer XGBoost may not load in an older one. Pin the version in your serving environment, and upgrade the serving library before the training one.
- Class labels.
XGBClassifierexpects labels0..n-1. If you encoded labels with aLabelEncoder, save the encoder too, or predictions will be integers you cannot map back.
Inspecting a saved model
Because JSON is plain text, you can open it directly. To see the trees in readable form, use get_dump:
import xgboost as xgb
booster = xgb.Booster()
booster.load_model("native.json")
print(booster.get_dump(dump_format="text")[0])This prints the first tree as nested split conditions and leaf values. It is a good way to confirm that a loaded model has the depth and number of trees you expect.
Exercise
A teammate trains a model on a pandas DataFrame, pickles it, and sends you the file. Your serving environment has a different XGBoost version, and you also receive an inference DataFrame whose columns are in a different order. Name two risks and the safer approach for each.
Show answer
Risk 1 is the pickle: it depends on matching Python and XGBoost versions and can execute arbitrary code when loaded. The safer approach is to have the teammate call savemodel to a .json or .ubj file and to pin the library version in serving. Risk 2 is column order: the model was trained with named features, so a different order raises a featurenames mismatch (or silently misaligns columns if names were absent). The safer approach is to reorder the inference columns to match booster.feature_names before predicting, and to store the expected feature list in a sidecar file.