我正在尝试可视化一个简单的决策树模型:
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>
感谢您的帮助
答案 0 :(得分:0)
使用pydot == 1.2.4
和scikit-learn == 0.19.1
(replaced 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
为无时返回。
out_file:文件对象或字符串,可选(默认='tree.dot') 输出文件的句柄或名称。如果是
None
,结果是 以字符串形式返回。这将是0.20版本的默认值。