create decision tree json in python

To create a decision tree in Python, you can use the scikit-learn library. Once you have trained your decision tree model, you can export it to a JSON file for further use. Here’s how you can do it:

main.py
from sklearn.tree import export_graphviz
import json

# `model` is your trained decision tree model
# `feature_names` is a list of feature names used in the model
# `class_names` is a list of target labels used in the model
def tree_to_json(model, feature_names, class_names):
    tree = export_graphviz(model, out_file=None,
                           feature_names=feature_names,
                           class_names=class_names,
                           filled=True, rounded=True,
                           special_characters=True)
    tree_json = json.loads(tree)
    return tree_json
594 chars
15 lines

In the code snippet above, export_graphviz is a function that exports the decision tree as a DOT file, which is a textual graph representation. We then use the json.loads function to parse the DOT file into a JSON object. You can then write this JSON object to a file or use it directly in your Python code as needed.

gistlibby LogSnag