Printing the tree after applying decison tree algo for classification in sklearn



Hi all,
After applying decision tree for the classification using following code :
from sklearn clf_tree=tree.DecisionTreeClassifier(),label_x)
I want to print the tree to see how the classification is happening. Please help.

Understand decision tree in jupiter notebook

Hi @ravi_6767, you could use the export_graphviz function for that


Try this code :

from sklearn import tree tree.export_graphviz(clf_tree,out_file='') from sklearn.externals.six import StringIO import pydot dot_data = StringIO() tree.export_graphviz(clf_tree, out_file=dot_data) graph = pydot.graph_from_dot_data(dot_data.getvalue()) a=graph.write_png("tree.png") from IPython.display import Image import os return Image(filename=os.getcwd()+'/tree.png')

Here only clf_tree is the variable that you have to look for which is :

from sklearn import tree clf_tree=tree.DecisionTreeClassifier(),label_x)

Note :Make sure to fit the data before using the code.
This is will save the file as .png extension and will show up in IPython notebook.
Hope this helps!


Thanks @jalFaizy and @syed.danish, that helped me a lot !!