Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert decision tree directly to png [duplicate]

I am trying to generate a decision tree which I want to visualize using dot. The resulting dotfile shall be converted to png.

While I can do the last conversion step in dos using something like

export_graphviz(dectree, out_file="graph.dot")

followed by a DOS command

dot -Tps graph.dot -o outfile.ps

doing all this directly in python dows not work and generates an error

AttributeError: 'list' object has no attribute 'write_png'

This is the program code I have tried:

from sklearn import tree  
import pydot
import StringIO

# Define training and target set for the classifier
train = [[1,2,3],[2,5,1],[2,1,7]]
target = [10,20,30]

# Initialize Classifier. Random values are initialized with always the same random seed of value 0 
# (allows reproducible results)
dectree = tree.DecisionTreeClassifier(random_state=0)
dectree.fit(train, target)

# Test classifier with other, unknown feature vector
test = [2,2,3]
predicted = dectree.predict(test)

dotfile = StringIO.StringIO()
tree.export_graphviz(dectree, out_file=dotfile)
graph=pydot.graph_from_dot_data(dotfile.getvalue())
graph.write_png("dtree.png")

What am I missing?

like image 958
tfv Avatar asked Oct 03 '16 06:10

tfv


1 Answers

I ended up using pydotplus:

from sklearn import tree  
import pydotplus
import StringIO

# Define training and target set for the classifier
train = [[1,2,3],[2,5,1],[2,1,7]]
target = [10,20,30]

# Initialize Classifier. Random values are initialized with always the same random seed of value 0 
# (allows reproducible results)
dectree = tree.DecisionTreeClassifier(random_state=0)
dectree.fit(train, target)

# Test classifier with other, unknown feature vector
test = [2,2,3]
predicted = dectree.predict(test)

dotfile = StringIO.StringIO()
tree.export_graphviz(dectree, out_file=dotfile)
graph=pydotplus.graph_from_dot_data(dotfile.getvalue())
graph.write_png("dtree.png")

EDIT: Thanks for the comment, to get this running in pydot I'd have to write:

(graph,)=pydot.graph_from_dot_data(dotfile.getvalue())
like image 165
tfv Avatar answered Oct 03 '22 17:10

tfv