AttributeError:“列表"对象没有属性"create_png" [英] AttributeError: 'list' object has no attribute 'create_png'
问题描述
这将数据分类为决策树.决策树已创建,但我无法查看决策树.
This classifies the data as a decision tree. The decision tree is created but I am not able to view the decision tree.
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())
推荐答案
函数pydot.graph_from_dot_data
返回 a list
在pydot
的早期版本相比).
The function pydot.graph_from_dot_data
returns a list
in pydot >= 1.2.0
(in contrast to earlier versions of pydot
).
原因是使输出均匀化,过去如果返回两个图,则为list
,但是如果返回单个图则为list
.这样的分支是用户代码错误的常见来源(简单优于复杂[[a href ="https://www.python.org/dev/peps/pep-0020/" rel ="nofollow noreferrer"> PEP 20 ]).
The reason was to homogenize the output, which in the past was a list
if two graphs were returned, but a graph if a single graph was returned. Such branching is a common source of errors in user code (simple is better than complex [PEP 20]).
更改适用于调用函数dot_parser.parse_dot_data
的所有函数,该函数现在返回
The change applies to all functions that call the function dot_parser.parse_dot_data
, which now returns a list
in all cases.
要解决该错误,您需要解压缩期望的单个图:
To address the error, you need to unpack the single graph that you expect:
(graph,) = pydot.graph_from_dot_data(dot_data.getvalue())
此语句还断言将返回单个图形.因此,如果这种假设不成立,并且返回了更多的图形,则解压缩将捕获该图形.相反,graph = (...)[0]
不会.
This statement also asserts that a single graph is returned. So if this assumption doesn't hold, and more graphs are returned, this unpacking will catch it. In contrast, graph = (...)[0]
won't.
相关的pydot
问题:
- https://github.com/erocarrera/pydot/issues/149
- https://github.com/erocarrera/pydot/issues/159
这篇关于AttributeError:“列表"对象没有属性"create_png"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!