-1

I'm trying to visualize a simple decision tree model :

import sklearn.datasets as datasets
import pandas as pd
iris=datasets.load_iris()
df=pd.DataFrame(iris.data, columns=iris.feature_names)
y=iris.target
from sklearn.tree import DecisionTreeClassifier
dtree=DecisionTreeClassifier()
dtree.fit(df,y)
from sklearn.externals.six import StringIO  
from IPython.display import Image  
from sklearn.tree import export_graphviz
import pydotplus
dot_data = StringIO()
export_graphviz(dtree, out_file=dot_data,  
            filled=True, rounded=True,
            special_characters=True)
graph = pydotplus.graph_from_dot_data(dot_data.getvalue())  
Image(graph.create_png())

I got this error: TypeError: add_node() received a non node class object: <pydotplus.graphviz.Node object at 0x000000000927A160>

Thanks for your help

0 _
  • 10,524
  • 11
  • 77
  • 109
toumz
  • 41
  • 4

1 Answers1

1

The following works for me without any errors, using pydot == 1.2.4 and scikit-learn == 0.19.1 (which replaced the package sklearn):

from IPython.display import Image  
import pandas as pd
import pydot
import sklearn.datasets as datasets
from sklearn.tree import DecisionTreeClassifier
from sklearn.tree import export_graphviz

iris = datasets.load_iris()
df = pd.DataFrame(iris.data, columns=iris.feature_names)
y = iris.target
dtree = DecisionTreeClassifier()
dtree.fit(df, y)
dot_data = export_graphviz(dtree, out_file=None,
                filled=True, rounded=True,
                special_characters=True)
(graph,) = pydot.graph_from_dot_data(dot_data)
Image(graph.create_png())

Also, there is no need to pass a StringIO object. As the docstring of the function sklearn.tree.export_graphviz says:

dot_data : string

String representation of the input tree in GraphViz dot format. Only returned if out_file is None.

beware of the default value though:

out_file : file object or string, optional (default='tree.dot') Handle or name of the output file. If None, the result is returned as a string. This will the default from version 0.20.

0 _
  • 10,524
  • 11
  • 77
  • 109