在scikit-learn中可视化决策树 [英] Visualizing decision tree in scikit-learn
问题描述
我正在尝试使用python中的scikit-learn设计一个简单的决策树(我正在Windows操作系统上使用Anaconda的Ipython Notebook和Python 2.7.3)并将其可视化如下:
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")
但是,出现以下错误:
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
不返回任何内容,因此默认情况下返回无
。
通过执行 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屋!