1

I got the below code from Visualizing a Decision Tree - Machine Learning import numpy as np from sklearn.datasets import load_iris from sklearn import tree

iris = load_iris()
test_idx = [0, 50 , 100]

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

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

I tried to run it in my python 3.5 but i get an error saying that graph is a list.

Traceback (most recent call last):
  File "Iris.py", line 31, in <module>
    graph.write_pdf("iris.pdf")
AttributeError: 'list' object has no attribute 'write_pdf'
Press any key to continue . . .

How come graph here is a list?

python novice
  • 379
  • 1
  • 4
  • 18

2 Answers2

2

I think this is a duplicate, here is answered the same question link

because pydot.graph_from_dot_data return a list the solution is:

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

This solved the problem for me with Python 3.6.5 :: Anaconda, Inc.

Sadmi
  • 311
  • 2
  • 15
0

Pydot will not work in Python3. You can use Pydotplus (graph.write_pdf("iris.pdf") AttributeError: 'list' object has no attribute 'write_pdf'") for python3 instead of pydot.

Although, the code shown on youtube is for Python2. So, it will be better if you use Python2.

Community
  • 1
  • 1
sansingh
  • 195
  • 8