Visualizing decision tree in scikit-learn

后端 未结 11 2194
广开言路
广开言路 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:14

    Here is one liner for those who are using jupyter and sklearn(18.2+) You don't even need matplotlib for that. Only requirement is graphviz

    pip install graphviz
    

    than run (according to code in question X is a pandas DataFrame)

    from graphviz import Source
    from sklearn import tree
    Source( tree.export_graphviz(dtreg, out_file=None, feature_names=X.columns))
    

    This will display it in SVG format. Code above produces Graphviz's Source object (source_code - not scary) That would be rendered directly in jupyter.

    Some things you are likely to do with it

    Display it in jupter:

    from IPython.display import SVG
    graph = Source( tree.export_graphviz(dtreg, out_file=None, feature_names=X.columns))
    SVG(graph.pipe(format='svg'))
    

    Save as png:

    graph = Source( tree.export_graphviz(dtreg, out_file=None, feature_names=X.columns))
    graph.format = 'png'
    graph.render('dtree_render',view=True)
    

    Get the png image, save it and view it:

    graph = Source( tree.export_graphviz(dtreg, out_file=None, feature_names=X.columns))
    png_bytes = graph.pipe(format='png')
    with open('dtree_pipe.png','wb') as f:
        f.write(png_bytes)
    
    from IPython.display import Image
    Image(png_bytes)
    

    If you are going to play with that lib here are the links to examples and userguide

提交回复
热议问题