2017-03-18 89 views
0

我想要在我的數據集上可視化應用決策樹分類器並查看它如何分支出來。做了幾次谷歌搜索,這個鏈接出現了。我很好,直到這行「f = tree.export_graphviz(clf,out_file = f)」這些代碼。Graphviz decsion樹

from sklearn.datasets import load_iris 
from sklearn import tree 
iris = load_iris() 
clf = tree.DecisionTreeClassifier() 
clf = clf.fit(iris.data, iris.target) 
with open("iris.dot", 'w') as f: 
...  f = tree.export_graphviz(clf, out_file=f) 

我的問題是在這段代碼之後我該如何可視化樹?根據鏈接「http://scikit-learn.org/stable/modules/tree.html」,我必須使用此代碼「點-Tpdf iris.dot -o iris.pdf」創建一個PDF文件。我不明白我應該在哪裏使用它?在Graphviz的點工具中?如果是的話,我得到這個錯誤「錯誤::語法錯誤附近'點'線1」

我將不勝感激,如果有人回答我的問題。謝謝。

回答

1

dot -Tpdf iris.dot -o iris.pdf是,你可以在bash.And使用,你應該有Graphviz的工具installed.For例如,你可以在Ubuntu上使用命令來安裝它的命令:sudo apt-get install graphviz

根據鏈接「http://scikit-learn.org/stable/modules/tree.html」,如果我們有Python模塊安裝pydotplus,我們可以在Python直接生成PDF文件(或任何其他支持的文件類型):

import pydotplus 
dot_data = tree.export_graphviz(clf, out_file=None) 
graph = pydotplus.graph_from_dot_data(dot_data) 
graph.write_pdf("iris.pdf") 

對於謝莉的評論,我添加以下代碼,這是完整的代碼運行在我的IPython的筆記本。

import pydotplus 
from sklearn.datasets import load_iris 
from sklearn import tree 
iris = load_iris() 
clf = tree.DecisionTreeClassifier() 
clf = clf.fit(iris.data, iris.target) 
with open("iris.dot", 'w') as f: 
    f = tree.export_graphviz(clf, out_file=f) 

dot_data = tree.export_graphviz(clf, out_file=None) 
graph = pydotplus.graph_from_dot_data(dot_data) 
graph.write_pdf("iris.pdf") 
+0

我已經安裝graphviz。問題出現在cmd中的代碼「dot -Tpdf tree.dot -o tree.pdf」。我得到這個錯誤錯誤:點:無法打開tree.dot – Shelly

+0

而當我想通過pydotplus做到這一點,我得到錯誤,當涉及到這一行「dot_data = tree.export_graphviz(clf,out_file =無) 」。該錯誤如下所示:AttributeError:'NoneType'對象沒有屬性'寫',我真的不明白爲什麼會出現這個錯誤。 – Shelly

+0

@Shelly 1.'「tree.dot」'應替換爲正確的點文件路徑。如果使用''dot -Tpdf tree.dot -o tree.pdf「,請確保您有一個tree.dot文件。 '。我在我的ipython筆記本上運行了官方文檔的代碼,沒有問題。我已將完整的代碼添加到我的答案中。 – xiaoyi