在 scikit-learn 中可视化决策树 [英] Visualizing decision tree in scikit-learn

查看:32
本文介绍了在 scikit-learn 中可视化决策树的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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 follows:

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

但是,我收到以下错误:

However, I get the following error:

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

我使用以下博客文章作为参考:博客链接

I use the following blog post as reference: Blogpost link

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

The following stackoverflow question doesn't seem to work for me as well: Question

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

Could someone help me with how to visualize the decision tree in scikit-learn?

推荐答案

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

通过执行 dotfile = tree.export_graphviz(...) 你覆盖了之前分配给 dotfile 的打开的文件对象,所以你会得到一个错误您尝试关闭文件(因为它现在 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()
...

这篇关于在 scikit-learn 中可视化决策树的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆