1、下载安装graphviz-2.38.msi url:http://www.graphviz.org/pub/graphviz/stable/windows/graphviz-2.38.msi
要是原链接下载不了,可以下我这个:http://download.csdn.net/detail/shouwangzhelv/9492517
2、pip install pydot
我这里安装完直接就可以import,没有错误。据说有的报错:不能导入dot_parser,这个可以直接安装:pip install -U pydot pyparsing==1.5.7
3、为了避免出错,我添加了系统路径:C:\Program Files (x86)\Graphviz2.38\bin 和 C:\Program Files (x86)\Graphviz2.38
然而还是出错了,说说问题及解决吧:
1、pywintypes.error: (2, 'RegOpenKeyEx', ...) 应该是没找到注册表,直接修改模块源文件让它找到就好了。
解决:修改Python2.7\Lib\site-packages\pydot.py,这是修改完的了,原文件没保存。
其实这个文件前面原来有method1和2,2是给linux用的(你的文件里应该有这些内容),对比了一下method1和3,发现3好点,其实不管method几,主要是为了获得path和progs,就找一种合适的方法能正确获得这两就好了。选用method3,作了如下修改,一切都正常了。。其实就是,不用他自动获取path了,直接给他一个path就好了,然后path对了, progs = __find_executables(path),progs也就对了。
def find_graphviz():
# Method 3 (Windows only)
#
if os.sys.platform == 'win32':
# Try and work out the equivalent of "C:\Program Files" on this
# machine (might be on drive D:, or in a different language)
#
if False:#os.environ.has_key('PROGRAMFILES'):
# Note, we could also use the win32api to get this
# information, but win32api may not be installed.
path = os.path.join(os.environ['PROGRAMFILES'], 'ATT', 'GraphViz', 'bin')
else:
#Just in case, try the default...
path = r"C:\Program Files (x86)\Graphviz2.38\bin"
progs = __find_executables(path)
if progs is not None :
#print "Used default install location"
return progs
for path in (
'/usr/bin', '/usr/local/bin',
'/opt/bin', '/sw/bin', '/usr/share',
'/Applications/Graphviz.app/Contents/MacOS/' ):
progs = __find_executables(path)
if progs is not None :
#print "Used path"
return progs
# Failed to find GraphViz
#
return None
问题2:pydot.InvocationException: GraphViz's executables not found
跟上面一个问题,按上面改了这个就不会出现了。
至此,graphviz和pydot就安装完了。
下面说说用法,画个决策树的图(默认你已经装了sklearn模块):
python源码:
#encoding:utf8 #Author:lvpengbin import sys reload(sys) sys.setdefaultencoding("utf-8") from sklearn.datasets import load_iris from sklearn import tree from sklearn.externals.six import StringIO import pydot iris = load_iris()#载入数据集 clf = tree.DecisionTreeClassifier()#算法模型 clf = clf.fit(iris.data, iris.target)#模型训练 dot_data = StringIO() tree.export_graphviz(clf, out_file=dot_data) graph = pydot.graph_from_dot_data(dot_data.getvalue()) graph.write_pdf("iris.pdf")#写入pdf
iris.pdf: