【问题标题】:Visualizing decision tree in scikit-learn在 scikit-learn 中可视化决策树
【发布时间】:2015-03-05 06:16:17
【问题描述】:

我正在尝试在 Python 中使用 scikit-learn 设计一个简单的决策树(我在 Windows 操作系统上使用 Anaconda 的 Ipython Notebook 和 Python 2.7.3)并将其可视化如下:

from pandas import read_csv, DataFrame
from sklearn import tree
from os import system

data = read_csv('D:/training.csv')
Y = data.Y
X = data.ix[:,"X0":"X33"]

dtree = tree.DecisionTreeClassifier(criterion = "entropy")
dtree = dtree.fit(X, Y)

dotfile = open("D:/dtree2.dot", 'w')
dotfile = tree.export_graphviz(dtree, out_file = dotfile, feature_names = X.columns)
dotfile.close()
system("dot -Tpng D:.dot -o D:/dtree2.png")

但是,我收到以下错误:

AttributeError: 'NoneType' object has no attribute 'close'

我使用以下博文作为参考:Blogpost link

以下 stackoverflow 问题似乎对我也不起作用:Question

有人可以帮助我如何在 scikit-learn 中可视化决策树吗?

【问题讨论】:

  • 文件dtree2.dot被创建了吗?
  • 你能否调试export_graphviz 行,因为它返回None,所以发生了一些错误
  • 是的。 dtree2.dot 确实被创建了。
  • Scikit-learn from version 0.21 有方法 plot_tree 比导出到 graphviz 更容易使用。无论如何,还有非常好的包dtreeviz。下面是sklearn树的可视化方法对比:blog post link

标签: python scikit-learn visualization decision-tree


【解决方案1】:

这是只需 3 行代码即可获得漂亮图形的最少代码:

from sklearn import tree
import pydotplus

dot_data=tree.export_graphviz(dt,filled=True,rounded=True)
graph=pydotplus.graph_from_dot_data(dot_data)
graph.write_png('tree.png')  

plt.imshow(plt.imread('tree.png'))

我刚刚添加了plt.imgshow 以在 Jupyter Notebook 中查看图表。如果您只对保存 png 文件感兴趣,可以忽略它。

我安装了以下依赖项:

pip3 install graphviz
pip3 install pydotplus

对于 MacO,Graphviz 的 pip 版本不起作用。在 Graphviz 的 official documentation 之后,我使用 brew 安装了它,一切正常。

brew install graphviz

【讨论】:

  • 这对我来说真的很有效。我建议任何寻求解决方案的人尝试使用 sklearn.datasets 中的 load_iris 示例数据库。
【解决方案2】:

Scikit learn 最近引入了plot_tree 方法来简化此操作(0.21 版(2019 年 5 月)中的新功能)。文档here

这是您需要的最少代码:

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 支持一些参数来美化树。例如:

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()

如果要将图片保存到文件中,请在plt.show()之前添加以下行:

plt.savefig('filename.png')

如果你想以文本格式查看规则,有一个答案here。阅读起来更直观。

【讨论】:

    【解决方案3】:

    pydotplus创建here的简单方法(必须安装graphviz):

    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())
    

    【讨论】:

      【解决方案4】:

      以下也可以正常工作:

      from sklearn.datasets import load_iris
      iris = load_iris()
      
      # Model (can also use single decision tree)
      from sklearn.ensemble import RandomForestClassifier
      model = RandomForestClassifier(n_estimators=10)
      
      # Train
      model.fit(iris.data, iris.target)
      # Extract single tree
      estimator = model.estimators_[5]
      
      from sklearn.tree import export_graphviz
      # Export as dot file
      export_graphviz(estimator, out_file='tree.dot', 
                      feature_names = iris.feature_names,
                      class_names = iris.target_names,
                      rounded = True, proportion = False, 
                      precision = 2, filled = True)
      
      # Convert to png using system command (requires Graphviz)
      from subprocess import call
      call(['dot', '-Tpng', 'tree.dot', '-o', 'tree.png', '-Gdpi=600'])
      
      # Display in jupyter notebook
      from IPython.display import Image
      Image(filename = 'tree.png')
      

      您可以找到来源here

      【讨论】:

        【解决方案5】:

        我复制并更改了您的部分代码,如下所示:

        from pandas import read_csv, DataFrame
        from sklearn import tree
        from sklearn.tree import DecisionTreeClassifier
        from os import system
        
        data = read_csv('D:/training.csv')
        Y = data.Y
        X = data.ix[:,"X0":"X33"]
        
        dtree = tree.DecisionTreeClassifier(criterion = "entropy")
        dtree = dtree.fit(X, Y)
        

        确定你有dtree后,即上面的代码运行良好,你添加下面的代码来可视化决策树:

        记得先安装graphviz:pip install graphviz

        import graphviz 
        from graphviz import Source
        dot_data = tree.export_graphviz(dtree, out_file=None, feature_names=X.columns)
        graph = graphviz.Source(dot_data) 
        graph.render("name of file",view = True)
        

        我尝试了我的数据,可视化效果很好,我立即查看了一个 pdf 文件。

        【讨论】:

          【解决方案6】:

          如果您在直接获取源 .dot 时遇到问题,您也可以像这样使用Source.from_file

          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')
          

          【讨论】:

            【解决方案7】:

            这里是为那些使用 jupyter 和 sklearn(18.2+) 的人准备的一个班轮,你甚至不需要 matplotlib。唯一的要求是graphviz

            pip install graphviz
            

            比运行(根据有问题的代码 X 是 pandas DataFrame)

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

            这将以 SVG 格式显示。上面的代码生成 Graphviz 的 Source 对象(source_code - 不可怕),它将直接在 jupyter 中呈现。

            你可能会用它做一些事情

            在 jupter 中显示:

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

            另存为png:

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

            获取png图片,保存并查看:

            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)
            

            如果您要使用该库,这里是指向 examplesuserguide 的链接

            【讨论】:

            • 这是在 Anaconda 中的安装方法:conda install -c conda-forge python-graphviz
            【解决方案8】:

            您可以复制 export_graphviz 文件的内容并将其粘贴到webgraphviz.com 站点。

            您可以查看有关如何visualize the decision tree in Python with graphviz 的文章以获取更多信息。

            【讨论】:

              【解决方案9】:

              如果你像我一样在安装 graphviz 时遇到问题,你可以通过

              来可视化树
              1. 使用export_graphviz 将其导出,如之前的答案所示
              2. 在文本编辑器中打开 .dot 文件
              3. 复制一段代码并粘贴@webgraphviz.com

              【讨论】:

                【解决方案10】:

                或者,您可以尝试使用 pydot 从 dot 生成 png 文件:

                ...
                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")
                ...
                

                【讨论】:

                • 在评论@Alexey Shrub 中查看新版本的 pydotplus
                【解决方案11】:

                sklearn.tree.export_graphviz 不返回任何内容,因此默认返回 None

                通过执行dotfile = tree.export_graphviz(...),您会覆盖之前分配给dotfile 的打开文件对象,因此当您尝试关闭文件时会出现错误(因为它现在是None)。

                要修复它,请将您的代码更改为

                ...
                dotfile = open("D:/dtree2.dot", 'w')
                tree.export_graphviz(dtree, out_file = dotfile, feature_names = X.columns)
                dotfile.close()
                ...
                

                【讨论】:

                • 这确实消除了错误,但以下命令不会产生绘图:system("dot -Tpng D:/dtree2.dot -o D:/dtree2.png")。但是,会创建 dtree2.dot 文件。
                • 对不起,我对使用graphviz一无所知。最好提出一个新问题,因为这完全是一个不同的问题。
                猜你喜欢
                • 2012-05-21
                • 2020-09-08
                • 2018-12-19
                • 2017-02-23
                • 2020-04-05
                • 2017-07-21
                • 1970-01-01
                • 2017-03-26
                相关资源
                最近更新 更多