Convert decision tree directly to png [duplicate]

夙愿已清 提交于 2020-12-01 10:50:35

问题


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?


回答1:


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())


来源:https://stackoverflow.com/questions/39825699/convert-decision-tree-directly-to-png

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!