我正在学习关于科舍特文档的决策树教程。我有pydotplus 2.0.2,但它告诉我它没有write方法-下面是错误的。我已经为它挣扎了一段时间了,有什么想法吗?非常感谢!
from sklearn import tree
from sklearn.datasets import load_iris
iris = load_iris()
clf = tree.DecisionTreeClassifier()
clf = clf.fit(iris.data, iris.target)
from IPython.display import Image
dot_data = tree.export_graphviz(clf, out_file=None)
import pydotplus
graph = pydotplus.graphviz.graph_from_dot_data(dot_data)
Image(graph.create_png())我的错误是
/Users/air/anaconda/bin/python /Users/air/PycharmProjects/kiwi/hemr.py
Traceback (most recent call last):
File "/Users/air/PycharmProjects/kiwi/hemr.py", line 10, in <module>
dot_data = tree.export_graphviz(clf, out_file=None)
File "/Users/air/anaconda/lib/python2.7/site-packages/sklearn/tree/export.py", line 375, in export_graphviz
out_file.write('digraph Tree {\n')
AttributeError: 'NoneType' object has no attribute 'write'
Process finished with exit code 1-更新
使用out_file修复程序会引发另一个错误:
Traceback (most recent call last):
File "/Users/air/PycharmProjects/kiwi/hemr.py", line 13, in <module>
graph = pydotplus.graphviz.graph_from_dot_data(dot_data)
File "/Users/air/anaconda/lib/python2.7/site-packages/pydotplus/graphviz.py", line 302, in graph_from_dot_data
return parser.parse_dot_data(data)
File "/Users/air/anaconda/lib/python2.7/site-packages/pydotplus/parser.py", line 548, in parse_dot_data
if data.startswith(codecs.BOM_UTF8):
AttributeError: 'NoneType' object has no attribute 'startswith'--更新2
另外,下面是我自己的答案,它解决了另一个问题
发布于 2016-10-10 12:02:41
问题是,您将参数out_file设置为None。
如果查看文档,如果将其设置为None,它将直接返回string文件,而不创建文件。当然,string没有write方法。
因此,应采取以下行动:
dot_data = tree.export_graphviz(clf)
graph = pydotplus.graphviz.graph_from_dot_data(dot_data)发布于 2016-10-22 12:15:18
方法graph_from_dot_data()在为out_file指定了适当的路径之后,也没有为我工作。
相反,尝试使用graph_from_dot_file方法:
graph = pydotplus.graphviz.graph_from_dot_file("iris.dot")发布于 2017-07-13 15:14:02
今天早上我也遇到了同样的错误。我使用python3.x,下面是解决这个问题的方法。
from sklearn import tree
from sklearn.datasets import load_iris
from IPython.display import Image
import io
iris = load_iris()
clf = tree.DecisionTreeClassifier()
clf = clf.fit(iris.data, iris.target)
# Let's give dot_data some space so it will not feel nervous any more
dot_data = io.StringIO()
tree.export_graphviz(clf, out_file=dot_data)
import pydotplus
graph = pydotplus.graphviz.graph_from_dot_data(dot_data.getvalue())
# make sure you have graphviz installed and set in path
Image(graph.create_png())如果您使用python2.x,我相信您需要将“导入io”更改为:
import StringIO和,
dot_data = StringIO.StringIO()希望能帮上忙。
https://stackoverflow.com/questions/39956430
复制相似问题