因为学习机器学习用到决策树,用pydot可以直接可视化出来决策树的模型。
遂直接pip安装了pydot模块,然而运行出错。
后来在网上搜索说使用pydot要预先安装pyparsing和GraphViz。
安装顺序:
1、下载安装GraphViz 链接: http://pan.baidu.com/s/1pKrvHUz 密码: hvmn
下载完后双击运行安装
在环境变量里添加C:\Python27\graphviz\bin即可(貌似现在安装过程会自动添加环境变量)
2、方法1——直接命令行进入python安装目录的scripts文件夹,运行pip install pydot
方法2——下载安装pydot 链接: http://pan.baidu.com/s/1dEmWlkX 密码: me48
cmd切换到解压后的pydot文件夹下,运行:python setup.py install 即可
重点:
本人安装后运行python代码出错信息:pydot.InvocationException: GraphViz's executables not found
出错原因:应该是没找到注册表,直接修改模块源文件让它找到就好了。
解决:参考了python的数据可视化 graphviz pydot安装配置(win10)——修改Python2.7\Lib\site-packages\pydot.py
找到python中的pydot.py文件,打开后直接定位到def find_graphviz():下的 # Method 3 (Windows only),直接把Method3的代码替换到下面的代码:
# 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"E:\360Install\Anaconda2\Graphviz 2.28\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
其中
E:\360Install\Anaconda2\Graphviz 2.28\bin是我的Graphviz\bin安装目录,大家改成自己安装的Graphviz\bin目录即可
最后,给出一段运行代码,如果运行成功说明pydot模块可用:
#encoding:utf8
#Author:lvpengbin
import sys
reload(sys)
sys.setdefaultencoding("utf-8")
from sklearn.datasets import load_iris #skit-learn是一个机器学习的开源包,需另外安装
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: