数据分析使用pydotplus可视化决策树

使用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版本和zip加压版本二者选择一。msi版本安装方便,不容易出错。
按照默认路径C:\Program Files (x86)安装,一直Next安装完成。
再将安装路径C:\Program Files (x86)\Graphviz2.38\bin添加到环境变量中:
添加到环境变量

Step 2:测试graphviz

测试graphviz是否安装成功:

windows测试安装成功
如果没有安装成功,在程序中使用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()))

下面是导出的可视化树形图:
Iris也可以导出PDF文件等。

欢迎各位关注我的个人公众号:HsuDan,我将分享更多自己的学习心得、避坑总结、面试经验、AI最新技术资讯。

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值