我试图生成一个决策树,我想使用点可视化。生成的dotfile应转换为png格式。
虽然我可以在dos中使用
来完成最后一个转换步骤export_graphviz(dectree, out_file="graph.dot")
后接DOS命令
dot -Tps graph.dot -o outfile.ps
直接在python中执行这些操作是行不通的,并且会生成一个错误
AttributeError: 'list' object has no attribute 'write_png'
这是我试过的程序代码:
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")
我错过了什么?
我最终使用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")
编辑:谢谢你的评论,要让这个在pydot中运行,我必须写:
(graph,)=pydot.graph_from_dot_data(dotfile.getvalue())