2017-08-31 149 views
1

我下面提供給一前一後的回答:Is it possible to print the decision tree in scikit-learn?使用的graphviz繪製決策樹蟒

from sklearn.datasets import load_iris 
from sklearn import tree 
from sklearn.externals.six import StringIO 
import pydot 

clf = tree.DecisionTreeClassifier() 
iris = load_iris() 

clf = clf.fit(iris.data, iris.target) 
tree.export_graphviz(clf, out_file='tree.dot') 
dot_data = StringIO() 
tree.export_graphviz(clf, out_file=dot_data) 
graph = pydot.graph_from_dot_data(dot_data.getvalue()) 
graph.write_pdf("iris.pdf") 

不幸的是,我無法弄清楚以下錯誤:

'list' object has no attribute 'write_pdf' 

有誰知道一個解決這個問題的方法是生成tree.dot文件的結構是一個列表?

更新

我已經使用Web應用程序http://webgraphviz.com/嘗試。但是,這樣做的結果是,決策樹條件和類不顯示。有沒有辦法將這些文件包含在tree.dot文件中?

回答

1

看起來像您在中收集的數據類型爲list

graph = pydot.graph_from_dot_data(dot_data.getvalue()) 
type(graph) 
<type 'list'> 

我們只對列表的第一個元素感興趣。 所以,你可以這樣做一個兩種方式下的,在那裏你收集 dot_data

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

1)變更線),或在收集整個名單,但只使用第一個元素被髮送到pdf

graph[0].write_pdf("iris.pdf") 

這裏是我得到的iris.pdf

01的輸出

enter image description here 更新

要解決路徑錯誤,

Exception: "dot.exe" not found in path.

here

安裝graphviz然後使用在你的代碼如下。

import os 
os.environ["PATH"] += os.pathsep + 'C:/Program Files (x86)/Graphviz2.38/bin/' 

或者只需將以下內容添加到控制面板中的Windows路徑。

C:\Program Files (x86)\Graphviz2.38\bin

graphviz文件,它不會在安裝過程中添加到Windows路徑。

+0

感謝您的回答。我一直在玩類似的解決方案,但留下了路徑中找不到的錯誤「」dot.exe「。」從閱讀來看,我認爲這個錯誤是由於我安裝了Graphiz? – Sjoseph

+1

請參閱我的路徑錯誤編輯。如果這解決了您的問題,請考慮接受作爲答案來關閉循環。 –