直接将决策树转换为png

2024-09-27 22:20:24 发布

您现在位置:Python中文网/ 问答频道 /正文

我正试图生成一个决策树,我想可视化使用点。生成的点文件应转换为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")

我错过了什么?


Tags: fromimporttreetargetpngexportoutdot
1条回答
网友
1楼 · 发布于 2024-09-27 22:20:24

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

相关问题 更多 >

    热门问题