Chedi Harabi
Chedi Harabi

Reputation: 13

AttributeError: 'list' object has no attribute 'write_pdf'

I started studying machine learning. I am following a google tutorial, but I face this error and the answers that I have found haven't work in my code. I'm not sure but it seems that the Python version has changed and doesn't use some library anymore.

This is the error:

[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'

This is the 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")

Upvotes: 0

Views: 1453

Answers (1)

Nir Alfasi
Nir Alfasi

Reputation: 53545

graph_from_dot_data returns a tuple, you have to explode it to get to the graph.

Change:

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

to:

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

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

Upvotes: 1

Related Questions