Python graph.write_pdf("iris.pdf") AttributeError: 'list' 对象没有属性 'write_pdf'

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/38176472/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 20:27:50  来源:igfitidea点击:

graph.write_pdf("iris.pdf") AttributeError: 'list' object has no attribute 'write_pdf'

pythonmachine-learningscikit-learngraphvizpydot

提问by u6523123

My code is follow the class of machine learning of google.The two code are same.I don't know why it show error.May be the type of variable is error.But google's code is same to me.Who has ever had this problem?

我的代码是按照google的机器学习类的。这两个代码是一样的。我不知道为什么会显示错误。可能是变量的类型是错误的。但是google的代码对我来说是一样的。谁有过这个问题?

This is error

这是错误

[0 1 2]
[0 1 2]
Traceback (most recent call last):
  File "/media/joyce/oreo/python/machine_learn/VisualizingADecisionTree.py", line 34, in <module>
    graph.write_pdf("iris.pdf")
AttributeError: 'list' object has no attribute 'write_pdf'
[Finished in 0.4s with exit code 1]
[shell_cmd: python -u "/media/joyce/oreo/python/machine_learn/VisualizingADecisionTree.py"]
[dir: /media/joyce/oreo/python/machine_learn]
[path: /usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games]

This is code

这是代码

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

采纳答案by Iliyan Bobev

pydot.graph_from_dot_data()returns a list, so try:

pydot.graph_from_dot_data()返回一个列表,所以尝试:

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

回答by avellable

I think you are using newer version of python. Please try with pydotplus.

我认为您使用的是较新版本的python。请尝试使用 pydotplus。

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

This should do it.

这应该这样做。

回答by Deepak Rao

I had exactly the same issue. Turned out that I hadn't installed graphviz. Once i did that it started to work.

我有完全相同的问题。原来我没有安装graphviz。一旦我这样做了,它就开始工作了。

回答by Jai

@Alex Sokolov, for my case in window, i downloaded and install / unzip the followingto a folder then setup the PATH in Windows environment variables. re-run the py code works for me. hope is helpful to you.

@Alex Sokolov,对于我在窗口中的情况,我下载并将以下内容安装/解压缩到一个文件夹中,然后在 Windows 环境变量中设置PATH。重新运行 py 代码对我有用。希望对你有帮助。

回答by LE SANG

I install scikit-learn via conda and all of about not work. Firstly, I have to install libtool

我通过 conda 安装了 scikit-learn,但一切都不起作用。首先,我必须安装 libtool

brew install libtool --universal

Then I follow this sklearn guideThen change the python file to this code

然后我按照这个sklearn指南然后将python文件更改为此代码

clf = clf.fit(train_data, train_target)
tree.export_graphviz(clf,out_file='tree.dot') 

Finally convert to png in terminal

最后在终端转换为png

dot -Tpng tree.dot -o tree.png

回答by Rakshitha Muranga Rodrigo

I tried the previous answers and still got a error when running the script Therefore, I just used pydotplus

我尝试了以前的答案,但在运行脚本时仍然出现错误因此,我只使用了pydotplus

import pydotplus

and install the "graphviz" by using:

并使用以下命令安装“ graphviz”:

sudo apt-get install graphviz

Then it worked for me, and I added

然后它对我有用,我补充说

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

Thanks to the previous contributors.

感谢之前的贡献者。

回答by Egypt_bird

It works as the following on Python3.7 but don't forget to install pydot using Anaconda prompt:

它在 Python3.7 上的工作方式如下,但不要忘记使用 Anaconda 提示符安装 pydot:

   from sklearn.externals.six import StringIO
   import pydot

   # viz code
   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[0].write_pdf('iris.pdf')

回答by Martin

I use Anaconda. Here's what worked for me: run from terminal:

我使用蟒蛇。这对我有用:从终端运行:

conda install python-graphviz
conda install pydot     ## don't forget this <-----------------

Then run

然后运行

clf = clf.fit(train_data, train_target)
tree.export_graphviz(clf,out_file='tree.dot')

Then from the terminal:

然后从终端:

dot -Tpng tree.dot -o tree.png

回答by WalkingClouds

To add all graphs for the number of your n_estimators you can do:

要为您的 n_estimators 数量添加所有图表,您可以执行以下操作:

for i in range(0, n):  #n is your n_estimators number
    dot_data = StringIO()
    tree.export_graphviz(clf.estimators_[i], out_file=dot_data, feature_names=iris.feature_names,
                        class_names=iris.target_names, filled=True, rounded=True,
                        impurity=False)
    graph = pydotplus.graph_from_dot_data(dot_data.getvalue())
    graph.write_pdf("iris%s.pdf"%i)

you could also switch the line

你也可以换线

graph = pydotplus.graph_from_dot_data(dot_data.getvalue())

for this one

对于这个

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

and it would still work.

它仍然有效。

回答by H1SWarrior

I hope this helps, I was having a similar issue. I decided not to use pydot / pydotplus, but rather graphviz. I modified (barely) the code and it works wonders! :)

我希望这会有所帮助,我遇到了类似的问题。我决定不使用 pydot / pydotplus,而是使用graphviz。我修改了(几乎)代码,它产生了奇迹!:)

# 2. Train classifier
# Testing Data
# Examples used to "test" the classifier's accuracy
# Not part of the training data
import numpy as np
from sklearn.datasets import load_iris
from sklearn import tree
iris = load_iris()
test_idx = [0, 50, 100] # Grabs one example of each flower for testing data (in the data set it so happens to be that
                        # each flower begins at 0, 50, and 100

# training data
train_target = np.delete(iris.target, test_idx)     # Delete all but 3 for training target data
train_data = np.delete(iris.data, test_idx, axis=0) # Delete all but 3 for training data

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

# create decision tree classifier and train in it on the testing data
clf = tree.DecisionTreeClassifier()
clf.fit(train_data, train_target)

# Predict label for new flower
print(test_target)
print(clf.predict(test_data))

# Visualize the tree
from sklearn.externals.six import StringIO
import graphviz
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 = graphviz.Source(dot_data.getvalue())
graph.render("iris.pdf", view=True)