Visualizing decision tree in scikit-learn

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

    Scikit learn recently introduced the plot_tree method to make this very easy (new in version 0.21 (May 2019)). Documentation here.

    Here's the minimum code you need:

    from sklearn import tree
    plt.figure(figsize=(40,20))  # customize according to the size of your tree
    _ = tree.plot_tree(your_model_name, feature_names = X.columns)
    plt.show()
    

    plot_tree supports some arguments to beautify the tree. For example:

    from sklearn import tree
    plt.figure(figsize=(40,20))  
    _ = tree.plot_tree(your_model_name, feature_names = X.columns, 
                 filled=True, fontsize=6, rounded = True)
    plt.show()
    

    If you want to save the picture to a file, add the following line before plt.show():

    plt.savefig('filename.png')
    

    If you want to view the rules in text format, there's an answer here. It's more intuitive to read.

提交回复
热议问题