背景描述:
python版本:3.6.3
IDE:pycharm
问题:
在pycharm上安装了graphviz和pydotplus等包,但是运行下面程序时,仍然会报错:
GraphViz's executables not found。
报错:
"F:\python\python project\learn & practise\venv2\Scripts\python.exe" E:/python_liao/0313-actual/0313_01_G635.py
Traceback (most recent call last):
File "E:/python_liao/0313-actual/0313_01_G635.py", line 48, in <module>
graph.write_pdf("G635_tree.pdf")
File "F:\python\python project\learn & practise\venv2\lib\site-packages\pydotplus\graphviz.py", line 1810, in <lambda>
prog=self.prog: self.write(path, format=f, prog=prog)
File "F:\python\python project\learn & practise\venv2\lib\site-packages\pydotplus\graphviz.py", line 1918, in write
fobj.write(self.create(prog, format))
File "F:\python\python project\learn & practise\venv2\lib\site-packages\pydotplus\graphviz.py", line 1960, in create
'GraphViz\'s executables not found')
pydotplus.graphviz.InvocationException: GraphViz's executables not found
程序:
import numpy as np
from sklearn import tree
from sklearn.tree
import DecisionTreeRegressor
import matplotlib.pyplot as plt
import pandas as pd
import pydotplus
# 生成CART决策回归树模型
regr_1 = DecisionTreeRegressor(max_depth=5)
regr_1.fit(data_x_train, data_y_train)
# 用模型regr_1进行预测
data_y_predict = regr_1.predict(data_x_test) ******************************************************************************************** 该部分生成了决策回归树的可视化图,分别为.dot和.pdf格式的可视化文档# 现在可以将模型存入dot文件:G635_tree.dot
with open("G635_tree.dot", 'w') as f:
f = tree.export_graphviz(regr_1, out_file=f)
# 可视化方法------------------------------------------
# 用pydotplus生成G635_tree.pdf。这样就不用再命令行去专门生成pdf文件了。
dot_data = tree.export_graphviz(regr_1, out_file=None)
graph = pydotplus.graph_from_dot_data(dot_data)
graph.write_pdf("G635_tree.pdf")
********************************************************************************************
# plot the results
plt.figure(figsize=(12, 9))
plt.plot(data_x_axix, data_y_predict, color="r", label="predict", linewidth=2)
plt.plot(data_x_axix, data_y_test, 'b', label="original")
plt.xlabel("data")
plt.ylabel("target")
plt.title("Decision Tree Regression")
plt.legend()
plt.show()
print('model:\n', regr_1)
解决方法:
参照http://blog.csdn.net/tina_ttl/article/details/51778551里面的方法,下载Graphviz的.zip文件,解压到一个路径下,得到“**graphviz-2.38\release\“这样的文件夹,然后把该路径利用os.path加入到程序里面,即可得到正常运行该程序。并且生成两个文档,可视化决策树的分类结果。
import os
os.environ["PATH"] += os.pathsep + 'F:/python/graphviz-2.38/release/bin/'
不知道具体原因,参考其他人的解答:
没有安装GraphViz‘s executables。我是用pip安装的Graphviz,但是Graphviz不是一个python tool,仍然需要安装GraphViz‘s executables,解决方法是
将GraphViz安装目录的bin目录放到环境变量的path路径中。
另附sklearn的简介:
(附一个学习的网址:http://sklearn.lzjqsdd.com/index.html)
自2007年发布以来,scikit-learn已经成为Python重要的机器学习库了。scikit-learn简称sklearn,支持包括分类、回归、降维和聚类四大机器学习算法。还包含了特征提取、数据处理和模型评估三大模块。
sklearn是Scipy的扩展,建立在NumPy和matplotlib库的基础上。利用这几大模块的优势,可以大大提高机器学习的效率。
sklearn拥有着完善的文档,上手容易,具有着丰富的API,在学术界颇受欢迎。sklearn已经封装了大量的机器学习算法,包括LIBSVM和LIBINEAR。同时sklearn内置了大量数据集,节省了获取和整理数据集的时间。