2016-10-03 47 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