6

I am trying to generate a decision tree which I want to visualize using dot. The resulting dotfile shall be converted to png.

While I can do the last conversion step in dos using something like

export_graphviz(dectree, out_file="graph.dot")

followed by a DOS command

dot -Tps graph.dot -o outfile.ps

doing all this directly in python dows not work and generates an error

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

This is the program code I have tried:

from sklearn import tree  
import pydot
import StringIO

# Define training and target set for the classifier
train = [[1,2,3],[2,5,1],[2,1,7]]
target = [10,20,30]

# Initialize Classifier. Random values are initialized with always the same random seed of value 0 
# (allows reproducible results)
dectree = tree.DecisionTreeClassifier(random_state=0)
dectree.fit(train, target)

# Test classifier with other, unknown feature vector
test = [2,2,3]
predicted = dectree.predict(test)

dotfile = StringIO.StringIO()
tree.export_graphviz(dectree, out_file=dotfile)
graph=pydot.graph_from_dot_data(dotfile.getvalue())
graph.write_png("dtree.png")

What am I missing?

tfv
  • 6,016
  • 4
  • 36
  • 67

1 Answers1

8

I ended up using pydotplus:

from sklearn import tree  
import pydotplus
import StringIO

# Define training and target set for the classifier
train = [[1,2,3],[2,5,1],[2,1,7]]
target = [10,20,30]

# Initialize Classifier. Random values are initialized with always the same random seed of value 0 
# (allows reproducible results)
dectree = tree.DecisionTreeClassifier(random_state=0)
dectree.fit(train, target)

# Test classifier with other, unknown feature vector
test = [2,2,3]
predicted = dectree.predict(test)

dotfile = StringIO.StringIO()
tree.export_graphviz(dectree, out_file=dotfile)
graph=pydotplus.graph_from_dot_data(dotfile.getvalue())
graph.write_png("dtree.png")

EDIT: Thanks for the comment, to get this running in pydot I'd have to write:

(graph,)=pydot.graph_from_dot_data(dotfile.getvalue())
tfv
  • 6,016
  • 4
  • 36
  • 67
  • 1
    Related post. http://stackoverflow.com/questions/5316206/converting-dot-to-png-in-python – Quazi Marufur Rahman Oct 03 '16 at 06:44
  • I could only install with `pip install pydotplus`, not with `conda install pydotplus` which caused `InvalidArchiveError('Error with archive C:\\Users\\Admin\\Anaconda3\\pkgs\\openssl-1.1.1d-he774522_2xysboxfd\\pkg-openssl-1.1.1d-he774522_2.tar.zst. You probably need to delete and re-download or re-create this file. Message from libarchive was:\n\nCould not unlink')` – questionto42 May 20 '20 at 09:52