Last active
May 24, 2024 23:59
-
-
Save WillKoehrsen/ff77f5f308362819805a3defd9495ffd to your computer and use it in GitHub Desktop.
How to visualize a single decision tree in Python
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from sklearn.datasets import load_iris | |
iris = load_iris() | |
# Model (can also use single decision tree) | |
from sklearn.ensemble import RandomForestClassifier | |
model = RandomForestClassifier(n_estimators=10) | |
# Train | |
model.fit(iris.data, iris.target) | |
# Extract single tree | |
estimator = model.estimators_[5] | |
from sklearn.tree import export_graphviz | |
# Export as dot file | |
export_graphviz(estimator, out_file='tree.dot', | |
feature_names = iris.feature_names, | |
class_names = iris.target_names, | |
rounded = True, proportion = False, | |
precision = 2, filled = True) | |
# Convert to png using system command (requires Graphviz) | |
from subprocess import call | |
call(['dot', '-Tpng', 'tree.dot', '-o', 'tree.png', '-Gdpi=600']) | |
# Display in jupyter notebook | |
from IPython.display import Image | |
Image(filename = 'tree.png') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This works! Thank you!