2016-03-07 119 views
2

我在玩決策樹算法並試圖繪製樹。然而,IDE報告以下錯誤:NameError:全局名稱'dot_parser'未定義

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 

我不知道如何來處理這個問題,因爲我已經試過卸載並重新安裝pydot丹pyparsing,這是在其他的答案提出的,但事實並非如此幫幫我。

這裏是我的代碼:

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

我使用python2.7和PyCharm運行,操作系統是win8.1。 感謝您的幫助。

+0

是否有堆棧跟蹤?或者也許減少代碼直到你得到所謂的[mcve]。這將有助於隔離問題。 –

+0

只需更新堆棧跟蹤。我完全困惑如何解決這個問題。你可以幫我嗎? – Wulipapa

+0

首先,嘗試通過隔離代碼的某些部分來創建[mcve],直到找到造成問題的確切行/模塊/包爲止。 Stacktrace已經有所幫助,因爲現在我們知道在調用'pydot.graph_from_dot_data'方法時這是一個問題。 –

回答

2

看起來您的錯誤是由於安裝順序不正確而缺少庫的一部分(pyparsing)。

herehere

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

的解決方案似乎是首先去除pydotpyparsing,然後安裝pyparsing第一,然後pydot

要安裝很可能會改變未來的版本,所以在目前看來你需要運行類似如下:(從this可愛的回答)

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 
+1

...有趣的是,卸載pyparsing打破了點和easy_install ...! – Tanasis

+0

@坦納斯是這樣嗎?我從來沒有這個問題,你有來源可以引用嗎? –

+0

在我做了'pip卸載pyparsing'之後,'pip install'會抱怨找不到'pyparsing'並且不起作用。我希望我會找到時間重現這一點,並貼上錯誤,但我現在很忙。 :( – Tanasis

2

對於我來說,我發現一個很好的提示是安裝pydotplus,因爲它與pyparsing v2.0及更高版本兼容。它還具有可以與Anaconda的graphviz安裝一起使用的優點。我正在使用Anaconda v2.4.1,並使用condas安裝Windows 7 x64和Graphviz 2.38。

1

我剛更新我的pydot1.2.3,並且錯誤消失。

sudo pip install -U pydot 
相關問題