2012-05-13 55 views
9

我是使用sciki-learn的noob,所以請耐心等待。可視化決策樹(來自scikit-learn的示例)

我正在經歷的例子: http://scikit-learn.org/stable/modules/tree.html#tree

>>> from sklearn.datasets import load_iris 
>>> from sklearn import tree 
>>> iris = load_iris() 
>>> clf = tree.DecisionTreeClassifier() 
>>> clf = clf.fit(iris.data, iris.target) 
>>> from StringIO import StringIO 
>>> out = StringIO() 
>>> out = tree.export_graphviz(clf, out_file=out) 

顯然,graphiz文件就可以使用了。

但是,如何使用graphiz文件繪製樹? (這個例子並沒有詳細描述樹如何繪製)。

示例代碼和提示比歡迎!

謝謝!


更新

我使用Ubuntu 12.04,Python的2.7.3

回答

6

你跑哪個操作系統?你有沒有安裝graphviz

在你的榜樣,StringIO()對象,持有Graphviz的數據,這裏有一個方法來檢查數據:

... 
>>> print out.getvalue() 

digraph Tree { 
0 [label="X[2] <= 2.4500\nerror = 0.666667\nsamples = 150\nvalue = [ 50. 50. 50.]", shape="box"] ; 
1 [label="error = 0.0000\nsamples = 50\nvalue = [ 50. 0. 0.]", shape="box"] ; 
0 -> 1 ; 
2 [label="X[3] <= 1.7500\nerror = 0.5\nsamples = 100\nvalue = [ 0. 50. 50.]", shape="box"] ; 
0 -> 2 ; 
3 [label="X[2] <= 4.9500\nerror = 0.168038\nsamples = 54\nvalue = [ 0. 49. 5.]", shape="box"] ; 
2 -> 3 ; 
4 [label="X[3] <= 1.6500\nerror = 0.0407986\nsamples = 48\nvalue = [ 0. 47. 1.]", shape="box"] ; 
3 -> 4 ; 
5 [label="error = 0.0000\nsamples = 47\nvalue = [ 0. 47. 0.]", shape="box"] ; 
4 -> 5 ; 
6 [label="error = 0.0000\nsamples = 1\nvalue = [ 0. 0. 1.]", shape="box"] ; 
4 -> 6 ; 
7 [label="X[3] <= 1.5500\nerror = 0.444444\nsamples = 6\nvalue = [ 0. 2. 4.]", shape="box"] ; 
3 -> 7 ; 
8 [label="error = 0.0000\nsamples = 3\nvalue = [ 0. 0. 3.]", shape="box"] ; 
7 -> 8 ; 
9 [label="X[0] <= 6.9500\nerror = 0.444444\nsamples = 3\nvalue = [ 0. 2. 1.]", shape="box"] ; 
7 -> 9 ; 
10 [label="error = 0.0000\nsamples = 2\nvalue = [ 0. 2. 0.]", shape="box"] ; 
9 -> 10 ; 
11 [label="error = 0.0000\nsamples = 1\nvalue = [ 0. 0. 1.]", shape="box"] ; 
9 -> 11 ; 
12 [label="X[2] <= 4.8500\nerror = 0.0425331\nsamples = 46\nvalue = [ 0. 1. 45.]", shape="box"] ; 
2 -> 12 ; 
13 [label="X[0] <= 5.9500\nerror = 0.444444\nsamples = 3\nvalue = [ 0. 1. 2.]", shape="box"] ; 
12 -> 13 ; 
14 [label="error = 0.0000\nsamples = 1\nvalue = [ 0. 1. 0.]", shape="box"] ; 
13 -> 14 ; 
15 [label="error = 0.0000\nsamples = 2\nvalue = [ 0. 0. 2.]", shape="box"] ; 
13 -> 15 ; 
16 [label="error = 0.0000\nsamples = 43\nvalue = [ 0. 0. 43.]", shape="box"] ; 
12 -> 16 ; 
} 

,你可以把它寫成.dot file併產生圖像的輸出,如源表明您鏈接:

$ dot -Tpng tree.dot -o tree.png(PNG格式輸出)

+0

嗨,謝謝!我使用Ubuntu 12.04,Python版本2.7.3。我想知道是否有,我可以在python腳本內而不是在命令行中執行它? – DjangoRocks

+1

當然,只要抓住[Python的綁定到graphviz](https://www.google.com/search?q=python+graphviz+binding)之一,你應該能夠從python shell – theta

+0

謝謝!這很有幫助! – DjangoRocks

4

你非常接近!只是做:

graph_from_dot_data(out.getvalue()).write_pdf("somefile.pdf") 
+1

只有當#classes足夠小以至於文本中的nvalue數組不會在行間被破壞...在這種情況下,我必須用''手動搜索/替換\ n(保留合法的當然)......有點痛苦。同一個熱門編碼標籤......他們會馬上發生錯誤。 – user1269942