Visualizing decision tree in scikit-learn

后端 未结 11 2160
广开言路
广开言路 2020-12-02 10:26

I am trying to design a simple Decision Tree using scikit-learn in Python (I am using Anaconda\'s Ipython Notebook with Python 2.7.3 on Windows OS) and visualize it as follo

相关标签:
11条回答
  • 2020-12-02 11:20

    If you run into issues with grabbing the source .dot directly you can also use Source.from_file like this:

    from graphviz import Source
    from sklearn import tree
    tree.export_graphviz(dtreg, out_file='tree.dot', feature_names=X.columns)
    Source.from_file('tree.dot')
    
    0 讨论(0)
  • 2020-12-02 11:22

    Alternatively, you could try using pydot for producing the png file from dot:

    ...
    tree.export_graphviz(dtreg, out_file='tree.dot') #produces dot file
    
    import pydot
    dotfile = StringIO()
    tree.export_graphviz(dtreg, out_file=dotfile)
    pydot.graph_from_dot_data(dotfile.getvalue()).write_png("dtree2.png")
    ...
    
    0 讨论(0)
  • 2020-12-02 11:24

    If, like me, you have a problem installing graphviz, you can visualize the tree by

    1. exporting it with export_graphviz as shown in previous answers
    2. Open the .dot file in a text editor
    3. Copy the piece of code and paste it @ webgraphviz.com
    0 讨论(0)
  • 2020-12-02 11:26

    sklearn.tree.export_graphviz doesn't return anything, and so by default returns None.

    By doing dotfile = tree.export_graphviz(...) you overwrite your open file object, which had been previously assigned to dotfile, so you get an error when you try to close the file (as it's now None).

    To fix it change your code to

    ...
    dotfile = open("D:/dtree2.dot", 'w')
    tree.export_graphviz(dtree, out_file = dotfile, feature_names = X.columns)
    dotfile.close()
    ...
    
    0 讨论(0)
  • 2020-12-02 11:26

    Simple way founded here with pydotplus (graphviz must be installed):

    from IPython.display import Image  
    from sklearn import tree
    import pydotplus # installing pyparsing maybe needed
    

    ...

    dot_data = tree.export_graphviz(best_model, out_file=None, feature_names = X.columns)
    graph = pydotplus.graph_from_dot_data(dot_data)
    Image(graph.create_png())
    
    0 讨论(0)
提交回复
热议问题