2016-07-27 34 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'])