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

decision_trees
python
sklearn

#1

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


Understand decision tree in jupiter notebook
#2

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


#3

@ravi_6767,
Try this code :

from sklearn import tree tree.export_graphviz(clf_tree,out_file='tree.dot') 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() clf_tree.fit(train_x,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!
Regards,
SD


#4

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