XGBoosting Home | About | Contact | Examples

Save XGBoost Model To JSON with scikit-learn

JSON (JavaScript Object Notation) is a lightweight, human-readable format for storing and transporting data.

Saving your XGBoost models in JSON format can enhance their portability and make them easier to use with other programming languages.

from sklearn.datasets import make_classification
from xgboost import XGBClassifier

# Generate a random classification dataset
X, y = make_classification(n_samples=1000, n_classes=2, random_state=42)

# Train an XGBoost model
model = XGBClassifier(n_estimators=100, learning_rate=0.1, random_state=42)
model.fit(X, y)

# save the model in json format
model.save_model('xgb_model.json')

# Load model from file
loaded_model = XGBClassifier()
loaded_model.load_model('xgb_model.json')

# Use the loaded model to make predictions
predictions = loaded_model.predict(X)

Here’s what we’re doing:

  1. We fit the model on the dataset.
  2. We save the fit model in JSON format using save_model() to the file xgb_model.json.
  3. We create a new XGBClassifier model and populate it with the fit model details from xgb_model.json using load_model().
  4. We use the loaded model to make a prediction


See Also