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:
- We fit the model on the dataset.
- We save the fit model in JSON format using
save_model()
to the filexgb_model.json
. - We create a new
XGBClassifier
model and populate it with the fit model details fromxgb_model.json
usingload_model()
. - We use the loaded model to make a prediction