将决策树直接转换为png [英] Convert decision tree directly to png

查看:117
本文介绍了将决策树直接转换为png的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试生成一个我想使用点进行可视化的决策树.生成的点文件应转换为 png.

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

虽然我可以使用类似的东西在 dos 中完成最后一个转换步骤

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

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

后跟一个 DOS 命令

followed by a DOS command

dot -Tps graph.dot -o outfile.ps

直接在 python dows 中执行所有这些操作不起作用并产生错误

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

我错过了什么?

推荐答案

我最终使用了 pydotplus:

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

感谢您的评论,要让它在 pydot 中运行,我必须写:

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

(graph,)=pydot.graph_from_dot_data(dotfile.getvalue())

这篇关于将决策树直接转换为png的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆