Python [Graphviz pydot]

时间:2018-01-11 12:12:25

标签: python graphviz pydot

我正在尝试可视化一个简单的决策树模型:

import sklearn.datasets as datasets
import pandas as pd
iris=datasets.load_iris()
df=pd.DataFrame(iris.data, columns=iris.feature_names)
y=iris.target
from sklearn.tree import DecisionTreeClassifier
dtree=DecisionTreeClassifier()
dtree.fit(df,y)
from sklearn.externals.six import StringIO  
from IPython.display import Image  
from sklearn.tree import export_graphviz
import pydotplus
dot_data = StringIO()
export_graphviz(dtree, out_file=dot_data,  
            filled=True, rounded=True,
            special_characters=True)
graph = pydotplus.graph_from_dot_data(dot_data.getvalue())  
Image(graph.create_png())

我收到此错误:TypeError: add_node()收到非节点类对象:<pydotplus.graphviz.Node object at 0x000000000927A160>

感谢您的帮助

1 个答案:

答案 0 :(得分:0)

使用pydot == 1.2.4scikit-learn == 0.19.1replaced the package sklearn)时,以下内容适用于我,没有任何错误:

from IPython.display import Image  
import pandas as pd
import pydot
import sklearn.datasets as datasets
from sklearn.tree import DecisionTreeClassifier
from sklearn.tree import export_graphviz

iris = datasets.load_iris()
df = pd.DataFrame(iris.data, columns=iris.feature_names)
y = iris.target
dtree = DecisionTreeClassifier()
dtree.fit(df, y)
dot_data = export_graphviz(dtree, out_file=None,
                filled=True, rounded=True,
                special_characters=True)
(graph,) = pydot.graph_from_dot_data(dot_data)
Image(graph.create_png())

此外,无需传递StringIO个对象。作为函数sklearn.tree.export_graphviz says

的文档字符串
  

dot_data:string

     

GraphViz点格式的输入树的字符串表示形式。     仅在out_file为无时返回。

谨防default value

  

out_file:文件对象或字符串,可选(默认='tree.dot')     输出文件的句柄或名称。如果是None,结果是     以字符串形式返回。这将是0.20版本的默认值。