Skip to content

Instantly share code, notes, and snippets.

@WillKoehrsen
Last active March 26, 2024 04:41
Show Gist options
  • Star 19 You must be signed in to star a gist
  • Fork 13 You must be signed in to fork a gist
  • Save WillKoehrsen/ff77f5f308362819805a3defd9495ffd to your computer and use it in GitHub Desktop.
Save WillKoehrsen/ff77f5f308362819805a3defd9495ffd to your computer and use it in GitHub Desktop.
How to visualize a single decision tree in Python
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')
@Arielcchy
Copy link

Note for thecml's solution - add Graphwiz to PATH:
https://stackoverflow.com/questions/35064304/runtimeerror-make-sure-the-graphviz-executables-are-on-your-systems-path-aft
,answered Jun 19 '17 at 8:43, Aprameyo Roy
works on Jupyter

@maheshkendre161
Copy link

maheshkendre161 commented Jun 11, 2022

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
tree

@atonui
Copy link

atonui commented Mar 26, 2024

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