I am trying to design a simple Decision Tree using scikit-learn in Python (I am using Anaconda\'s Ipython Notebook with Python 2.7.3 on Windows OS) and visualize it as follo
If you run into issues with grabbing the source .dot directly you can also use Source.from_file
like this:
from graphviz import Source
from sklearn import tree
tree.export_graphviz(dtreg, out_file='tree.dot', feature_names=X.columns)
Source.from_file('tree.dot')
Alternatively, you could try using pydot for producing the png file from dot:
...
tree.export_graphviz(dtreg, out_file='tree.dot') #produces dot file
import pydot
dotfile = StringIO()
tree.export_graphviz(dtreg, out_file=dotfile)
pydot.graph_from_dot_data(dotfile.getvalue()).write_png("dtree2.png")
...
If, like me, you have a problem installing graphviz, you can visualize the tree by
export_graphviz
as shown in previous answers.dot
file in a text editorsklearn.tree.export_graphviz doesn't return anything, and so by default returns None
.
By doing dotfile = tree.export_graphviz(...)
you overwrite your open file object, which had been previously assigned to dotfile
, so you get an error when you try to close the file (as it's now None
).
To fix it change your code to
...
dotfile = open("D:/dtree2.dot", 'w')
tree.export_graphviz(dtree, out_file = dotfile, feature_names = X.columns)
dotfile.close()
...
Simple way founded here with pydotplus (graphviz must be installed):
from IPython.display import Image
from sklearn import tree
import pydotplus # installing pyparsing maybe needed
...
dot_data = tree.export_graphviz(best_model, out_file=None, feature_names = X.columns)
graph = pydotplus.graph_from_dot_data(dot_data)
Image(graph.create_png())