Tourism-Package / export_model_artifacts.py
sathishaiuse's picture
Create export_model_artifacts.py
d3d9f4e verified
# export_model_artifacts.py
import joblib, xgboost as xgb, os
p = "best_overall_XGBoost.joblib"
m = joblib.load(p)
print("Loaded:", type(m))
# If pipeline, extract preprocessing and classifier
preproc_path = None
json_path = None
clf = m
try:
# sklearn Pipeline -> try to find the xgb step
from sklearn.pipeline import Pipeline
if isinstance(m, Pipeline):
# Save pipeline without the final estimator
steps = m.steps
# assume last step is classifier
*prefix, (last_name, last_obj) = steps
# Build preprocessor pipeline if any prefix exists
if prefix:
from sklearn.pipeline import Pipeline as SKPipeline
preproc = SKPipeline(prefix)
preproc_path = "preprocessor.joblib"
joblib.dump(preproc, preproc_path)
print("Saved preprocessor to", preproc_path)
clf = last_obj
except Exception as e:
print("Not a Pipeline or failed to extract pipeline:", e)
# If clf is XGBClassifier, get booster
try:
booster = None
if hasattr(clf, "get_booster"):
booster = clf.get_booster()
elif isinstance(clf, xgb.Booster):
booster = clf
else:
print("Classifier type:", type(clf))
if booster is not None:
json_path = "best_overall_XGBoost.json"
booster.save_model(json_path)
print("Saved booster JSON to", json_path)
except Exception as e:
print("Failed to export booster JSON:", e)
import traceback; traceback.print_exc()