matPlotLib绘制决策树
上篇中,实现了创建决策树但并不直观,这里学习绘制决策树,便于直观理解。
Matplotlib提供了名为pylab的模块,其中包括了许多numpy和pyplot中常用的函数,方便用户快速进行计算和绘图,
可以用于IPython中的快速交互式使用。
Matplotlib中的快速绘图的函数库可以通过如下语句载入:
- import matplotlib.pyplot as plt
import matplotlib.pyplot as plt
绘制树形图,我们需要定义树和叶的形态,还必须要知道有多少个叶节点和判断节点,还有树的层数,这样才能确定树的大小,绘制绘图区
首先注解绘制的树节点和叶节点以及箭头
- #定义文本框和箭头格式
- decisionNode = dict(boxstyle=”sawtooth”, fc=“0.8”) #定义判断节点形态
- leafNode = dict(boxstyle=”round4”, fc=“0.8”) #定义叶节点形态
- arrow_args = dict(arrowstyle=”<-“) #定义箭头
- #绘制带箭头的注解
- #nodeTxt:节点的文字标注, centerPt:节点中心位置,
- #parentPt:箭头起点位置(上一节点位置), nodeType:节点属性
- def plotNode(nodeTxt, centerPt, parentPt, nodeType):
- createPlot.ax1.annotate(nodeTxt, xy=parentPt, xycoords=’axes fraction’,
- xytext=centerPt, textcoords=’axes fraction’,
- va=”center”, ha=“center”, bbox=nodeType, arrowprops=arrow_args )
#定义文本框和箭头格式
decisionNode = dict(boxstyle=”sawtooth”, fc=”0.8”) #定义判断节点形态
leafNode = dict(boxstyle=”round4”, fc=”0.8”) #定义叶节点形态
arrow_args = dict(arrowstyle=”<-“) #定义箭头
#绘制带箭头的注解 #nodeTxt:节点的文字标注, centerPt:节点中心位置, #parentPt:箭头起点位置(上一节点位置), nodeType:节点属性 def plotNode(nodeTxt, centerPt, parentPt, nodeType): createPlot.ax1.annotate(nodeTxt, xy=parentPt, xycoords='axes fraction', xytext=centerPt, textcoords='axes fraction', va="center", ha="center", bbox=nodeType, arrowprops=arrow_args )
然后得到叶节点的数目和树的层数
- #计算叶节点数
- def getNumLeafs(myTree):
- numLeafs = 0
- firstStr = myTree.keys()[0]
- secondDict = myTree[firstStr]
- for key in secondDict.keys():
- if type(secondDict[key]).__name__==‘dict’:#是否是字典
- numLeafs += getNumLeafs(secondDict[key]) #递归调用getNumLeafs
- else: numLeafs +=1 #如果是叶节点,则叶节点+1
- return numLeafs
- #计算数的层数
- def getTreeDepth(myTree):
- maxDepth = 0
- firstStr = myTree.keys()[0]
- secondDict = myTree[firstStr]
- for key in secondDict.keys():
- if type(secondDict[key]).__name__==‘dict’:#是否是字典
- thisDepth = 1 + getTreeDepth(secondDict[key]) #如果是字典,则层数加1,再递归调用getTreeDepth
- else: thisDepth = 1
- #得到最大层数
- if thisDepth > maxDepth:
- maxDepth = thisDepth
- return maxDepth
#计算叶节点数
def getNumLeafs(myTree):numLeafs = 0firstStr = myTree.keys()[0] secondDict = myTree[firstStr] for key in secondDict.keys():if type(secondDict[key]).__name__=='dict':#是否是字典numLeafs += getNumLeafs(secondDict[key]) #递归调用getNumLeafselse: numLeafs +=1 #如果是叶节点,则叶节点+1return numLeafs
#计算数的层数 def getTreeDepth(myTree): maxDepth = 0 firstStr = myTree.keys()[0] secondDict = myTree[firstStr] for key in secondDict.keys(): if type(secondDict[key]).__name__=='dict':#是否是字典 thisDepth = 1 + getTreeDepth(secondDict[key]) #如果是字典,则层数加1,再递归调用getTreeDepth else: thisDepth = 1 #得到最大层数 if thisDepth > maxDepth: maxDepth = thisDepth return maxDepth有了注解和计算树形图的位置的参数,就可以绘制树形图了
为了清晰简明,在父子节点之间加入文本标签信息
- #在父子节点间填充文本信息
- #cntrPt:子节点位置, parentPt:父节点位置, txtString:标注内容
- def plotMidText(cntrPt, parentPt, txtString):
- xMid = (parentPt[0]-cntrPt[0])/2.0 + cntrPt[0]
- yMid = (parentPt[1]-cntrPt[1])/2.0 + cntrPt[1]
- createPlot.ax1.text(xMid, yMid, txtString, va=”center”, ha=“center”, rotation=30)
#在父子节点间填充文本信息
#cntrPt:子节点位置, parentPt:父节点位置, txtString:标注内容 def plotMidText(cntrPt, parentPt, txtString): xMid = (parentPt[0]-cntrPt[0])/2.0 + cntrPt[0] yMid = (parentPt[1]-cntrPt[1])/2.0 + cntrPt[1] createPlot.ax1.text(xMid, yMid, txtString, va="center", ha="center", rotation=30)然后绘制树形图;
- #绘制树形图
- #myTree:树的字典, parentPt:父节点, nodeTxt:节点的文字标注
- def plotTree(myTree, parentPt, nodeTxt):
- numLeafs = getNumLeafs(myTree) #树叶节点数
- depth = getTreeDepth(myTree) #树的层数
- firstStr = myTree.keys()[0] #节点标签
- #计算当前节点的位置
- cntrPt = (plotTree.xOff + (1.0 + float(numLeafs))/2.0/plotTree.totalW, plotTree.yOff)
- plotMidText(cntrPt, parentPt, nodeTxt) #在父子节点间填充文本信息
- plotNode(firstStr, cntrPt, parentPt, decisionNode) #绘制带箭头的注解
- secondDict = myTree[firstStr]
- plotTree.yOff = plotTree.yOff - 1.0/plotTree.totalD
- for key in secondDict.keys():
- if type(secondDict[key]).__name__==‘dict’:#判断是不是字典,
- plotTree(secondDict[key],cntrPt,str(key)) #递归绘制树形图
- else: #如果是叶节点
- plotTree.xOff = plotTree.xOff + 1.0/plotTree.totalW
- plotNode(secondDict[key], (plotTree.xOff, plotTree.yOff), cntrPt, leafNode)
- plotMidText((plotTree.xOff, plotTree.yOff), cntrPt, str(key))
- plotTree.yOff = plotTree.yOff + 1.0/plotTree.totalD
- #创建绘图区
- def createPlot(inTree):
- fig = plt.figure(1, facecolor=‘white’)
- fig.clf()
- axprops = dict(xticks=[], yticks=[])
- createPlot.ax1 = plt.subplot(111, frameon=False, **axprops)
- plotTree.totalW = float(getNumLeafs(inTree)) #树的宽度
- plotTree.totalD = float(getTreeDepth(inTree)) #树的深度
- plotTree.xOff = -0.5/plotTree.totalW; plotTree.yOff = 1.0;
- plotTree(inTree, (0.5,1.0), ”)
- plt.show()
#绘制树形图
#myTree:树的字典, parentPt:父节点, nodeTxt:节点的文字标注 def plotTree(myTree, parentPt, nodeTxt): numLeafs = getNumLeafs(myTree) #树叶节点数 depth = getTreeDepth(myTree) #树的层数 firstStr = myTree.keys()[0] #节点标签 #计算当前节点的位置 cntrPt = (plotTree.xOff + (1.0 + float(numLeafs))/2.0/plotTree.totalW, plotTree.yOff) plotMidText(cntrPt, parentPt, nodeTxt) #在父子节点间填充文本信息 plotNode(firstStr, cntrPt, parentPt, decisionNode) #绘制带箭头的注解 secondDict = myTree[firstStr] plotTree.yOff = plotTree.yOff - 1.0/plotTree.totalD for key in secondDict.keys(): if type(secondDict[key]).__name__=='dict':#判断是不是字典, plotTree(secondDict[key],cntrPt,str(key)) #递归绘制树形图 else: #如果是叶节点 plotTree.xOff = plotTree.xOff + 1.0/plotTree.totalW plotNode(secondDict[key], (plotTree.xOff, plotTree.yOff), cntrPt, leafNode) plotMidText((plotTree.xOff, plotTree.yOff), cntrPt, str(key)) plotTree.yOff = plotTree.yOff + 1.0/plotTree.totalD #创建绘图区 def createPlot(inTree): fig = plt.figure(1, facecolor='white') fig.clf() axprops = dict(xticks=[], yticks=[]) createPlot.ax1 = plt.subplot(111, frameon=False, **axprops) plotTree.totalW = float(getNumLeafs(inTree)) #树的宽度 plotTree.totalD = float(getTreeDepth(inTree)) #树的深度 plotTree.xOff = -0.5/plotTree.totalW; plotTree.yOff = 1.0; plotTree(inTree, (0.5,1.0), '') plt.show()其中createPlot()是主函数,创建绘图区,计算树形图的尺寸大小,它调用plotTree()等函数,plotTree()递归画出整个树形图。
加载之前创建了tree模块和这个treeplot模块,在命令提示符下输入
- >>> import treeplot
- >>> import tree
- >>> myDat,labels = tree.createDataSet()
- >>> myTree = tree.createTree(myDat,labels)
- >>> treeplot.createPlot(myTree)
>>> import treeplot
>>> import tree
>>> myDat,labels = tree.createDataSet()
>>> myTree = tree.createTree(myDat,labels)
>>> treeplot.createPlot(myTree)
得到正确的树形图
用创建的tree模块和treeplot模块,使用决策树预测隐形眼镜类型;
在命令提示符下输入
- >>> import tree
- >>> import treeplot
- >>> fr = open(’lenses.txt’)
- >>> lenses = [inst.strip().split(’\t’) for inst in fr.readlines()]
- >>> lensesLabels = [’age’,‘prescript’,‘astigmatic’,‘tearRate’]
- >>> lensesTree = tree.createTree(lenses,lensesLabels)
- >>> treeplot.createPlot(lensesTree)
>>> import tree
>>> import treeplot
>>> fr = open('lenses.txt')
>>> lenses = [inst.strip().split('\t') for inst in fr.readlines()]
>>> lensesLabels = ['age','prescript','astigmatic','tearRate']
>>> lensesTree = tree.createTree(lenses,lensesLabels)
>>> treeplot.createPlot(lensesTree)
得到如下所示
如有不足,请指出,谢谢~~
matPlotLib绘制决策树相关推荐
- python sklearn 绘制决策树模型的节点图
绘制决策树的图片可以使用sklearn.tree.plot_tree这个方法 详情可以参考官方文档:https://scikit-learn.org/stable/modules/generated/ ...
- Python+matplotlib绘制散点图模拟心型图案
推荐教材: <Python数据分析.挖掘与可视化>(慕课版)(ISBN:978-7-115-52361-7),董付国,人民邮电出版社,定价49.8元,2020年1月出版,2021年3月第6 ...
- python绘制决策树图片
背景 w3cshool机器学习篇最后一个章节是决策树的简单入门教学,我在那里拷贝代码运行时报错,显示绘制不出决策树图片 思路 python编译报错无非三种,语法错误,没有装库,路径没对.w3cshoo ...
- 【机器学习实战】构建/绘制决策树(ID3/C4.5)
近来想要整理一下机器学习实验的代码,将一些基本算法的过程重新整理实现,并完善注释. 一.构建决策树 1.计算信息熵calculate_entropy(dataset) 2.按某一特征划分数据集spli ...
- python中如何画出决策树_使用Python绘制决策树
决策树为字典格式,示例如下: {'tearRate': {'reduced': 'no lenses', 'normal': {' astigmatic': {'yes': {' prescript' ...
- python绘制决策树
前言:在使用python绘制决策树的时候,需要使用到matplotlib库,要想使用matplotlib库可以直接安装anaconda就可以了,anaconda中包含了许多的python科学计算库.在 ...
- 决策树(Decision Tree) | 绘制决策树
01 起 在这篇文章中,我们讲解了如何训练决策树,然后我们得到了一个字典嵌套格式的决策树结果,这个结果不太直观,不能一眼看着这颗"树"的形状.分支.属性值等,怎么办呢? 本文就上文 ...
- matplotlib绘制图表,设置刻度标签、最大最小刻度、字体大小,label位置、刻度轴箭头等
matplotlib绘制图表,设置刻度标签.最大最小刻度.字体大小,label位置.刻度轴箭头等 1. 效果图 2. 源码 2.1 仅使用普通轴ax + fontdict 源码 2.2 使用mpl设置 ...
- 使用KMeanCluster对多个区域进行聚类,并结合Matplotlib绘制中心点、最大最小距离点
使用KMeanCluster对多个区域进行聚类,并结合Matplotlib绘制中心点.最大最小距离点 1. 效果图 2. 源码 2.1 原始数据--xq.txt 2.2 源码 参考 这篇博客将演示如何 ...
最新文章
- shiro 实现登录验证功能
- 破解世界性技术难题! GTS让分布式事务简单高效
- Python3文件操作:with...open的使用代码示例
- matlab colorbar采用对数,matlab colorbar的使用 | 學步園
- Chrome Version 19.0.1055.1 dev Flash Missing plug-in的修复
- 网友的有趣发现:冬天里,欧洲古建筑上的雕像都好像“生病了”
- 区块链六-Merkle Tree
- 如何减少silverlight XAP包的尺寸
- info index.php,真 · nginx配置php文件解析(PATH_INFO支持与index.php隐藏)
- 月球 dem_通过“月球灾害”应对错误信息的流行
- GDI+学习及代码总结之------画刷Brush .
- 【SQL】数据库模糊查询
- Google Earth Browser Plugin (谷歌 地球 浏览器 插件) 下载地址 5.0
- 主要几个浏览器的内核是什么
- Linux【实操篇】—— 进程管理、服务管理、软件包管理(rpm、yum)
- 看完还不会数据库优化,你来找我!
- 瑞星微RK3288开发板
- idea的git报错You have not concluded your merge
- 2020年数学建模国赛B题题目和解题思路
- IEEE754标准转换
热门文章
- 20172313 2017-2018-2 《程序设计与数据结构》第十周学习总结
- 手把手教你webpack3(3)入口(多入口)entry
- Android零基础入门第20节:CheckBox和RadioButton使用大全
- SQL SERVER 数据库邮件配置
- php 获取http headers
- Oracle 12c 归档模式更改
- SBO中流程控制功能的实现-SBO_SP_TransactionNotification
- IBM Webpshere6(WAS6) bug发现一例
- 黄金的商品属性,货币属性,金融属性
- how can you save more space at home?