Python:NameError:全局名称' dot_parser'没有定义

时间:2015-05-08 15:12:38

标签: python

Python对我来说相当新鲜。

我正在尝试使用Scikit"运行用于Python的机器学习的泰坦机器学习示例。书。使用决策树的分类工作正常(clf已正确定义)但如果我想可视化决策树(请参阅下面的代码片段),我收到以下错误消息(从IPython复制)。

---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-34-15b1b4a5d909> in <module>()
      3 dot_data = StringIO.StringIO()
      4 tree.export_graphviz(clf, out_file = dot_data, feature_names = ['PClass', 'AgeFill', 'Gender'])
----> 5 graph = pydot.graph_from_dot_data(dot_data.getvalue())
      6 graph.write_png('titanic.png')

C:\Users\885299\AppData\Local\Continuum\Anaconda32\lib\site-packages\pydot.pyc in graph_from_dot_data(data)

    218     """
    219 
--> 220     return dot_parser.parse_dot_data(data)
    221 
    222 
NameError: global name 'dot_parser' is not defined

有人能帮助我吗?

我使用的代码段(类似于本书)是:

import pydot, StringIO

dot_data = StringIO.StringIO()
tree.export_graphviz(clf, out_file = dot_data, feature_names = ['Class', 'Age', 'Gender'])
graph = pydot.graph_from_dot_data(dot_data.getvalue())
graph.write_png('titanic.png')

from IPython.core.display import Image
Image(filename = 'titanic.png')

5 个答案:

答案 0 :(得分:1)

如果您使用的是Python 3,使用pydotplus而不是pydot对我来说很好。

Here is the github repo

答案 1 :(得分:0)

github上似乎有related issue。建议是确保您已经安装了pyparser库并更新它们。&#34;但是,我很确定它们是指pyparsing库。

您可以通过运行pip install pyparsing

来安装pyparsing

您可以通过运行pip install -U pyparsing

来更新pyparsing

此外,related stackoverflow question建议卸载pyparsing,然后重新安装pyparsing和pydot。

答案 2 :(得分:0)

我也强烈建议使用pydotplus而不是pydot(似乎pydot和Python3存在问题)。

这篇博文对我有所帮助: http://www.sas-programming.com/2015/04/sklearn-decisiontree-plot-example-needs.html

答案 3 :(得分:0)

我使用了以下内容并使用Python3。 Pyparser 2.2.0与pydot兼容。

pip install pyparsing==2.2.0
pip install pydot

安装了pydot 1.2.3。

如果您之前安装了任何pydot软件包,请先使用pip uninstall pydot将其卸载,然后按照上述步骤进行全新安装。

答案 4 :(得分:0)

很棒的解决方案谢谢。我在Ubuntu 14.04上遇到了同样的问题。只需几句话:当我尝试卸载pyparsing和pydot时,我遇到了错误:

不在OS拥有的/usr/lib/python2.7/dist-packages中卸载pydot

我解决了升级pip的问题 sudo pip install --upgrade pip

然后按照以下命令: sudo -H pip uninstall pydot sudo -H pip uninstall pyparsing 并重新安装: sudo -H pip install pyparsing sudo -H pip install pydot