File size: 772 Bytes
05211e9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
"""Export the trained Random Forest to model.json so a browser can run it (no server needed)."""
import json
import joblib

bundle = joblib.load("model.joblib")
model, classes = bundle["model"], bundle["classes"]

trees = []
for est in model.estimators_:
    t = est.tree_
    values = t.value[:, 0, :]
    probs = (values / values.sum(axis=1, keepdims=True)).round(6).tolist()
    trees.append({
        "left": t.children_left.tolist(),
        "right": t.children_right.tolist(),
        "feature": t.feature.tolist(),
        "threshold": [float(x) for x in t.threshold],
        "probs": probs,
    })

with open("model.json", "w") as f:
    json.dump({"classes": classes, "trees": trees}, f, separators=(",", ":"))
print(f"Saved model.json with {len(trees)} trees")