AttributeError:' list'对象没有属性' create_png'

时间:2017-08-08 13:31:05

标签: python-3.x machine-learning graphviz decision-tree pydot

这将数据分类为决策树。决策树已创建,但我无法查看决策树。

import numpy as np
from sklearn import linear_model, datasets, tree
import matplotlib.pyplot as plt
iris = datasets.load_iris()
f = open('decision_tree_data.txt')
x_train = []
y_train = []
for line in f:
    line = np.asarray(line.split(),dtype = np.float32)
    x_train.append(line[:-1])
    y_train.append(line[:-1])
x_train = np.asmatrix(x_train)
y_train = np.asmatrix(y_train)
model = tree.DecisionTreeClassifier()
model.fit(x_train,y_train)
from sklearn.externals.six import StringIO
import pydot
from IPython.display import Image
dot_data = StringIO()
tree.export_graphviz(model, out_file=dot_data,  
                     feature_names=iris.feature_names,  
                     class_names=iris.target_names,  
                     filled=True, rounded=True,  
                     special_characters=True)  
graph = pydot.graph_from_dot_data(dot_data.getvalue()) 
Image(graph.create_png())

1 个答案:

答案 0 :(得分:1)

函数pydot.graph_from_dot_data returns一个list in pydot >= 1.2.0(与早期版本的pydot相反)。

原因是输出均匀化,如果返回两个图形,则过去为list,但如果返回单个图形,则为图形。这种分支是用户代码中常见的错误来源(简单比复杂[PEP 20]更好。)

此更改适用于调用函数dot_parser.parse_dot_data的所有函数,现在返回a list in all cases

要解决此错误,您需要解压缩您期望的单个图表:

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

此语句还断言返回单个图。因此,如果这个假设不成立,并且返回了更多图表,那么这个解包将会捕获它。相反,graph = (...)[0]不会。

相关的pydot问题: