pythonscikit-learnjupyter-notebookdecision-tree

displaying scikit decision tree figure in jupyter notebook


I am currently creating a machine learning jupyter notebook as a small project and wanted to display my decision trees. However, all options I can find are to export the graphics and then load a picture, which is rather complicated.

Therefore, I wanted to ask whether there is a way to display my decision trees directly without exporting and loading graphics.


Solution

  • There is a simple library called graphviz which you can use to view your decision tree. In this you don't have to export the graphic, it'll directly open the graphic of tree for you and you can later decide if you want to save it or not. You can use it as following -

    import graphviz
    from sklearn.tree import DecisionTreeClassifier()
    from sklearn import tree
    
    clf = DecisionTreeClassifier()
    clf.fit(trainX,trainY)
    columns=list(trainX.columns)
    dot_data = tree.export_graphviz(clf,out_file=None,feature_names=columns,class_names=True)
    graph = graphviz.Source(dot_data)
    graph.render("image",view=True)
    f = open("classifiers/classifier.txt","w+")
    f.write(dot_data)
    f.close()
    

    because of view = True your graphs will open up as soon as they're rendered but if you don't want that and just want to save graphs, you can use view = False

    Hope this helps