2016-10-03 168 views
0

我正在试图生成一个决策树,我想要使用点可视化。得到的点文件将被转换为png。直接将决策树转换为PNG

虽然我可以使用像

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

接着在DOS命令

dot -Tps graph.dot -o outfile.ps 

直接在Python DOWS做这一切的东西不起作用做在DOS下最后转换步骤,并产生一个错误

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

我错过了什么?

回答

0

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

相关岗位。 http://stackoverflow.com/questions/5316206/converting-dot-to-png-in-python – qmaruf