决策树代码
from sklearn.datasets import load_iris
import pydotplus
from IPython.display import Image
from sklearn import tree
#训练模型
iris=load_iris()
clf=tree.DecisionTreeClassifier()
clf=clf.fit(iris.data,iris.target)
#绘图
dot_data=tree.export_graphviz(decision_tree=clf,
out_file=None,
rounded=True,
filled=True,
feature_names=iris.feature_names)
graph=pydotplus.graph_from_dot_data(dot_data)
Image(graph.create_png())
安装
安装pydotplus
pip install pydotplus
运行报错: GraphViz’s executables not found
安装graphviz
pip install graphviz
运行仍报错: GraphViz’s executables not found
查阅资料后,Graphviz属于一个独立的软件,需要到官网下载安装
网站:http://www.graphviz.org/Download
添加环境变量
有两种方法,亲测推荐第二种
第一种 环境变量中增加GraphViz的bin目录的路径
第二种 os方法
cmd中
python
进入python环境
import os
os.environ["PATH"]+= os.pathsep+"C:/Program Files/Graphviz/bin" # 换成你自己的Graphviz路径
大功告成!!!
运行结果
如果和我一样是在jupyter notebook中使用的话,需要重启jupyter notebook