使用 graphviz 在 python 中绘制决策树

Using graphviz to plot decision tree in python

我正在关注之前 post 的答案:Is it possible to print the decision tree in scikit-learn?

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 文件的结构是一个列表?

更新

我尝试使用网络应用程序 http://webgraphviz.com/。这有效,但是,不显示决策树条件以及 类。有什么方法可以将它们包含在 tree.dot 文件中吗?

您在 graph 中收集的数据似乎属于 list.

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

我们只对列表的第一个元素感兴趣。 因此,您可以通过以下两种方式之一来执行此操作,

1) 将 graph 中收集 dot_data 值的行更改为

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

2) 或者在 graph 中收集整个列表,但只使用第一个元素发送到 pdf

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

这是我得到的 iris.pdf

的输出

更新

要绕过路径错误,

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 路径。