【问题标题】:AttributeError: 'list' object has no attribute 'write_pdf'AttributeError:“列表”对象没有属性“write_pdf”
【发布时间】:2019-11-01 13:36:28
【问题描述】:

我开始学习机器学习。我正在关注谷歌教程,但我遇到了这个错误,我发现的答案在我的代码中不起作用。我不确定,但似乎 Python 版本已更改并且不再使用某些库。

这是错误:

[0 1 2]
[0 1 2]

Warning (from warnings module):
  File "C:\Users\Moi\AppData\Local\Programs\Python\Python37-32\lib\site-packages\sklearn\externals\six.py", line 31
    "(https://pypi.org/project/six/).", DeprecationWarning)
DeprecationWarning: The module is deprecated in version 0.21 and will be removed in version 0.23 since we've dropped support for Python 2.7. Please rely on the official version of six (https://pypi.org/project/six/).
Traceback (most recent call last):
  File "C:\Users\Moi\Desktop\python\ML\decision tree.py", line 30, in <module>
    graph.write_pdf("iris.pdf")
AttributeError: 'list' object has no attribute 'write_pdf'

这是代码:

import numpy as np
from sklearn.datasets import load_iris
from sklearn import tree
iris = load_iris ()
test_idx = [0,50,100]

#training data
train_target = np.delete(iris.target ,test_idx)
train_data = np.delete(iris.data, test_idx, axis= 0)

#testing data
test_target = iris.target [test_idx]
test_data = iris.data[test_idx]

clf = tree.DecisionTreeClassifier ()
clf.fit (train_data, train_target)
print (test_target )
print (clf.predict (test_data))
# viz code
from sklearn.externals.six import StringIO
import pydot
dot_data =StringIO()
tree.export_graphviz(clf,
        out_file=dot_data,
        feature_names=iris.feature_names,
        class_names=iris.target_names,
        filled= True, rounded=True,
        impurity=False)
graph = pydot.graph_from_dot_data(dot_data.getvalue())
graph.write_pdf("iris.pdf")

【问题讨论】:

  • 版本问题与错误无关,只是警告您以后将无法使用sklearn.externals.six。错误是因为graph 是一个无法直接导出为 pdf 的 python 列表(这也可能不是您想要的),如果您链​​接了您正在遵循的教程,这将非常有帮助,这样我们就可以看到那些试图做。

标签: python python-3.7


【解决方案1】:

graph_from_dot_data 返回一个元组,你必须分解它才能得到图表。

变化:

graph = pydot.graph_from_dot_data(dot_data.getvalue())
graph.write_pdf("iris.pdf")

到:

(graph,) = pydot.graph_from_dot_data(dot_data.getvalue())
graph.write_pdf("iris.pdf")

信用:https://www.programcreek.com/python/example/84621/pydot.graph_from_dot_data

【讨论】:

  • TypeError: 'Dot' object is not subscriptable
  • @ChediHarabi 这是一个新问题,请单独发布(作为一个新问题)并附上所有相关信息:代码、哪一行引发错误、堆栈跟踪(如果可用)等
猜你喜欢
  • 2021-07-05
  • 2018-01-16
  • 2016-05-14
  • 2016-12-21
  • 2022-01-23
  • 2022-01-23
  • 2021-08-23
  • 2016-04-22
  • 2019-12-28
相关资源
最近更新 更多