File size: 1,507 Bytes
d3d9f4e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
# 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()