2016-07-27 116 views
0

我使用一個「文本」下面的代碼二元分類問題:export_graphviz和可視化DT

def visualize_tree(tree,feature_names): 
    dot_data = StringIO() 
    export_graphviz(tree, 
        out_file=dot_data, 
        feature_names=feature_names, 
        special_characters=True)   
    graph = pydot.graph_from_dot_data(dot_data.getvalue(),) 
    graph.write_pdf("iris.pdf") 

vec = CountVectorizer(lowercase=True, tokenizer=tokens2, binary=True, ngram_range=(1,2)) 
x = vec.fit_transform(X_train) 
clf1 = DecisionTreeClassifier() 
clf1.fit(x, y_train)  
visualize_tree(clf1, vec.get_feature_names()) 

當我使用它沒有feature_names=feature_names,它會產生一個美麗的樹像這樣的: enter image description here

然而,當我添加feature_names=feature_names,額外的細節添加到樹,它給了我下面的「半棵樹」 !:

enter image description here 所有在一行中沒有任何箭頭!任何想法爲什麼?有沒有其他方法可以嘗試?

+0

很奇怪,你可以創建一個小例子,爲什麼發生這種情況?如果你在'DecisionTreeClassifier'中設置了'max_depth = 2',它還會發生嗎? – maxymoo

+0

即使在DecisionTreeClassifier中設置了max_depth = 2,它也不構造樹! – Ophilia

+0

你可以嘗試更改'out_file ='tree.dot'',然後使用'dot -Tpdf tree.dot -o tree.pdf'從命令行生成pdf嗎? – maxymoo

回答

1

而不是使用pydot,你可以使用graphviz的命令行,如果你想成爲看上你可以從你的代碼subprocess稱之爲:

import subprocess 

export_graphviz(model, 
       out_file='tree.dot', 
       feature_names=feature_names) 

subprocess.call(['dot', '-Tpdf', 'tree.dot', '-o' 'tree.pdf'])