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 hidden or 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') |
Hi, installing Graphwiz on Windows makes the script work on Windows. Remember to add Graphwiz to PATH for current user. https://graphviz.org/download/
This works! Thank you!
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Use below command in your terminal if you are using ubuntu 20.04
sudo apt-get install graphviz
Before this i was getting below error
Traceback (most recent call last):
File "visualize_decision_tree.py", line 23, in
call(['dot', '-Tpng', 'tree.dot', '-o', 'tree.png', '-Gdpi=600'])
File "/usr/lib/python3.8/subprocess.py", line 340, in call
with Popen(*popenargs, **kwargs) as p:
File "/usr/lib/python3.8/subprocess.py", line 858, in init
self._execute_child(args, executable, preexec_fn, close_fds,
File "/usr/lib/python3.8/subprocess.py", line 1704, in _execute_child
raise child_exception_type(errno_num, err_msg, err_filename)
FileNotFoundError: [Errno 2] No such file or directory: 'dot'
Then I got result
