AttributeError:“列表”对象没有属性“create_png”

Posted

技术标签:

【中文标题】AttributeError:“列表”对象没有属性“create_png”【英文标题】:AttributeError: 'list' object has no attribute 'create_png' 【发布时间】:2018-01-16 02:36:39 【问题描述】:

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

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())

【问题讨论】:

欢迎来到 ***。请阅读并遵循帮助文档中的发布指南。 Minimal, complete, verifiable example 适用于此。在您发布 MCVE 代码并准确描述问题之前,我们无法有效地帮助您。我们应该能够将您发布的代码粘贴到文本文件中并重现您描述的问题。最值得注意的是,我们需要您提供整个错误消息以及足够的数据来帮助我们解决问题。 总的来说,graph 似乎是一个列表,而不是预期的 pydot 对象。您是否错过了todot 转换?对不起;我不是这个包的专家。 也许您应该尝试安装 pydotplus,并将代码中的 pydot 替换为 pydotplus。 Pydot 似乎有几年不活跃了。 “无法查看”是什么意思,是否为空白,是否收到错误消息,是否收到乱码等? @Prune 当我打印我得到的图表时:[] 【参考方案1】:

函数 pydot.graph_from_dot_data returns a 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问题:

https://github.com/erocarrera/pydot/issues/149 https://github.com/erocarrera/pydot/issues/159

【讨论】:

以上是关于AttributeError:“列表”对象没有属性“create_png”的主要内容,如果未能解决你的问题,请参考以下文章

AttributeError:“列表”对象在转换为数组时没有属性“形状”

AttributeError:“列表”对象没有属性“排序值”

Keras AttributeError:“列表”对象没有属性“ndim”

AttributeError: 'property' 对象没有属性 'copy' - 尝试在 Django Rest 中获取对象列表时

AttributeError:“列表”对象没有属性“barh”

AttributeError 列表对象没有属性添加