使用Python进行数据分析过程中,需要可视化决策树模型:了解每个节点的决策是如何判断的,还有整个树的结构是如何?
下面是使用pydotplus库得到可视化的决策树图形。
个人的环境配置:
- python 3.6
- anacoda 4
- win 7 64位
Step 1 :下载graphviz
计算机安装graphviz:
Windows版本下载网址:https://graphviz.gitlab.io/_pages/Download/Download_windows.html
msi版本安装方便,不容易出错。
按照默认路径C:\Program Files (x86)安装,一直Next安装完成。
再将安装路径C:\Program Files (x86)\Graphviz2.38\bin添加到环境变量中:
Step 2:测试graphviz
测试graphviz是否安装成功:
如果没有安装成功,在程序中使用export_graphviz会继续出现报错:
InvocationException: GraphViz's executables not found
Step 3:安装pydotplus
pip install pyplotplus
安装好后可以正常使用,下面使用iris数据生成一个决策树,可视化决策树的分类:
from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
from sklearn.tree import DecisionTreeClassifier, export_graphviz
import pydotplus
from IPython.display import display, Image
import os
os.environ["PATH"] += os.pathsep + 'C:/Program Files (x86)/Graphviz2.38/bin/'
iris = load_iris()
x = iris.data
y = iris.target
x_train,x_test,y_train,y_test=train_test_split(x,y,test_size=0.2,random_state=0)
dtc = DecisionTreeClassifier(criterion='entropy') #建立决策树对象
dtc.fit(x_train, y_train) #决策树拟合
y_test_pre = dtc.predict(x_test) #预测
dtc.score(x_test, y_test)
dot_data = export_graphviz(dtc,out_file=None,feature_names=iris.feature_names,class_names=iris.target_names,filled=True,rounded=True,special_characters=True)
graph = pydotplus.graph_from_dot_data(dot_data)
graph.write_png('iris.png')
graph.write_pdf('iris.pdf')
display(Image(graph.create_png()))
下面是导出的可视化树形图:
也可以导出PDF文件等。
欢迎各位关注我的个人公众号:HsuDan,我将分享更多自己的学习心得、避坑总结、面试经验、AI最新技术资讯。