问题
I was playing with the decision tree algorithm and trying to plot the tree. However the IDE reported following error:
Couldn't import dot_parser, loading of dot files will not be possible.
<class 'pandas.core.frame.DataFrame'>
Traceback (most recent call last):
File "C:/Users/s152730/Desktop/exe1.py", line 70, in <module>
graph = pydot.graph_from_dot_data(test.getvalue())
File "C:\Python27\lib\site-packages\pydot.py", line 220, in graph_from_dot_data
return dot_parser.parse_dot_data(data)
NameError: global name 'dot_parser' is not defined
I have no idea how to deal with this problem because I've tried to uninstall and reinstall both pydot dan pyparsing, which was proposed in other answers, but it didn't help.
Here is my code:
from sklearn.tree import DecisionTreeClassifier
from sklearn.tree import ExtraTreeClassifier
from sklearn import tree
from sklearn.externals.six import StringIO
import pydot
from IPython.display import Image
test = StringIO()
tree.export_graphviz(clf, out_file=test, feature_names = attribute_names)
graph = pydot.graph_from_dot_data(test.getvalue())
graph.writepng('test.png')
image(filename = 'test.png')
I am using python2.7 and running on PyCharm, the OS is win8.1. Thanks for your help.
回答1:
It seems your error is that you are missing part of a library (pyparsing
) because of incorrect order of installation.
See here and here
Obvious to the initiated but not to the newbie: The workaround is to install pyparsing < 2.0.0 prior to installing pydot (or a package that depends on pydot.)
$ pip install pyparsing==1.5.7
The solution seems to be to first remove pydot
and pyparsing
, and then to install pyparsing
first, then pydot
.
The versions of which to install will most likely change in the future, so at the moment it seems you need to run something like the following: (taken from this lovely answer)
pip uninstall pyparsing
pip install -Iv https://pypi.python.org/packages/source/p/pyparsing/pyparsing-1.5.7.tar.gz#md5=9be0fcdcc595199c646ab317c1d9a709
pip install pydot
回答2:
For me, I found a great tip is to install pydotplus instead, as it is compatible with pyparsing v2.0 and greater. It also has the advantage that it can work with the graphviz installation from Anaconda. I'm using Anaconda v2.4.1 and on Windows 7 x64 and Graphviz 2.38 installed using condas.
回答3:
I've just update my pydot
to 1.2.3
, and the error disappears.
sudo pip install -U pydot
来源:https://stackoverflow.com/questions/35847269/nameerror-global-name-dot-parser-is-not-defined