将决策树直接转换为png

时间:2016-10-03 06:33:36

标签: python scikit-learn

我正在尝试生成一个我想用点可视化的决策树。生成的dotfile应转换为png。

虽然我可以使用像

这样的东西在dos中完成最后一个转换步骤
export_graphviz(dectree, out_file="graph.dot")

后跟DOS命令

dot -Tps graph.dot -o outfile.ps

在python dows中直接执行所有这些操作无效并生成错误

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

我错过了什么?

1 个答案:

答案 0 :(得分:1)

我最终使用了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())