上篇中,实现了创建决策树但并不直观,这里学习绘制决策树,便于直观理解。

Matplotlib提供了名为pylab的模块,其中包括了许多numpy和pyplot中常用的函数,方便用户快速进行计算和绘图,

可以用于IPython中的快速交互式使用。

Matplotlib中的快速绘图的函数库可以通过如下语句载入:

[python] view plain copyprint?
  1. import matplotlib.pyplot as plt
import matplotlib.pyplot as plt

绘制树形图,我们需要定义树和叶的形态,还必须要知道有多少个叶节点和判断节点,还有树的层数,这样才能确定树的大小,绘制绘图区

首先注解绘制的树节点和叶节点以及箭头

[python] view plain copyprint?
  1. #定义文本框和箭头格式
  2. decisionNode = dict(boxstyle=”sawtooth”, fc=“0.8”) #定义判断节点形态
  3. leafNode = dict(boxstyle=”round4”, fc=“0.8”) #定义叶节点形态
  4. arrow_args = dict(arrowstyle=”<-“) #定义箭头
  5. #绘制带箭头的注解
  6. #nodeTxt:节点的文字标注, centerPt:节点中心位置,
  7. #parentPt:箭头起点位置(上一节点位置), nodeType:节点属性
  8. def plotNode(nodeTxt, centerPt, parentPt, nodeType):
  9. createPlot.ax1.annotate(nodeTxt, xy=parentPt,  xycoords=’axes fraction’,
  10. xytext=centerPt, textcoords=’axes fraction’,
  11. 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 )

然后得到叶节点的数目和树的层数

[python] view plain copyprint?
  1. #计算叶节点数
  2. def getNumLeafs(myTree):
  3. numLeafs = 0
  4. firstStr = myTree.keys()[0]
  5. secondDict = myTree[firstStr]
  6. for key in secondDict.keys():
  7. if type(secondDict[key]).__name__==‘dict’:#是否是字典
  8. numLeafs += getNumLeafs(secondDict[key]) #递归调用getNumLeafs
  9. else:   numLeafs +=1 #如果是叶节点,则叶节点+1
  10. return numLeafs
  11. #计算数的层数
  12. def getTreeDepth(myTree):
  13. maxDepth = 0
  14. firstStr = myTree.keys()[0]
  15. secondDict = myTree[firstStr]
  16. for key in secondDict.keys():
  17. if type(secondDict[key]).__name__==‘dict’:#是否是字典
  18. thisDepth = 1 + getTreeDepth(secondDict[key]) #如果是字典,则层数加1,再递归调用getTreeDepth
  19. else:   thisDepth = 1
  20. #得到最大层数
  21. if thisDepth > maxDepth:
  22. maxDepth = thisDepth
  23. 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有了注解和计算树形图的位置的参数,就可以绘制树形图了

为了清晰简明,在父子节点之间加入文本标签信息

[python] view plain copyprint?
  1. #在父子节点间填充文本信息
  2. #cntrPt:子节点位置, parentPt:父节点位置, txtString:标注内容
  3. def plotMidText(cntrPt, parentPt, txtString):
  4. xMid = (parentPt[0]-cntrPt[0])/2.0 + cntrPt[0]
  5. yMid = (parentPt[1]-cntrPt[1])/2.0 + cntrPt[1]
  6. 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)然后绘制树形图;

[python] view plain copyprint?
  1. #绘制树形图
  2. #myTree:树的字典, parentPt:父节点, nodeTxt:节点的文字标注
  3. def plotTree(myTree, parentPt, nodeTxt):
  4. numLeafs = getNumLeafs(myTree)  #树叶节点数
  5. depth = getTreeDepth(myTree)    #树的层数
  6. firstStr = myTree.keys()[0]     #节点标签
  7. #计算当前节点的位置
  8. cntrPt = (plotTree.xOff + (1.0 + float(numLeafs))/2.0/plotTree.totalW, plotTree.yOff)
  9. plotMidText(cntrPt, parentPt, nodeTxt) #在父子节点间填充文本信息
  10. plotNode(firstStr, cntrPt, parentPt, decisionNode) #绘制带箭头的注解
  11. secondDict = myTree[firstStr]
  12. plotTree.yOff = plotTree.yOff - 1.0/plotTree.totalD
  13. for key in secondDict.keys():
  14. if type(secondDict[key]).__name__==‘dict’:#判断是不是字典,
  15. plotTree(secondDict[key],cntrPt,str(key))        #递归绘制树形图
  16. else:   #如果是叶节点
  17. plotTree.xOff = plotTree.xOff + 1.0/plotTree.totalW
  18. plotNode(secondDict[key], (plotTree.xOff, plotTree.yOff), cntrPt, leafNode)
  19. plotMidText((plotTree.xOff, plotTree.yOff), cntrPt, str(key))
  20. plotTree.yOff = plotTree.yOff + 1.0/plotTree.totalD
  21. #创建绘图区
  22. def createPlot(inTree):
  23. fig = plt.figure(1, facecolor=‘white’)
  24. fig.clf()
  25. axprops = dict(xticks=[], yticks=[])
  26. createPlot.ax1 = plt.subplot(111, frameon=False, **axprops)
  27. plotTree.totalW = float(getNumLeafs(inTree)) #树的宽度
  28. plotTree.totalD = float(getTreeDepth(inTree)) #树的深度
  29. plotTree.xOff = -0.5/plotTree.totalW; plotTree.yOff = 1.0;
  30. plotTree(inTree, (0.5,1.0), ”)
  31. 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模块,在命令提示符下输入

[python] view plain copyprint?
  1. >>> import treeplot
  2. >>> import tree
  3. >>> myDat,labels = tree.createDataSet()
  4. >>> myTree = tree.createTree(myDat,labels)
  5. >>> treeplot.createPlot(myTree)
>>> import treeplot
>>> import tree
>>> myDat,labels = tree.createDataSet()
>>> myTree = tree.createTree(myDat,labels)
>>> treeplot.createPlot(myTree)

得到正确的树形图


用创建的tree模块和treeplot模块,使用决策树预测隐形眼镜类型;

在命令提示符下输入

[python] view plain copyprint?
  1. >>> import tree
  2. >>> import treeplot
  3. >>> fr = open(’lenses.txt’)
  4. >>> lenses = [inst.strip().split(’\t’) for inst in fr.readlines()]
  5. >>> lensesLabels = [’age’,‘prescript’,‘astigmatic’,‘tearRate’]
  6. >>> lensesTree = tree.createTree(lenses,lensesLabels)
  7. >>> 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绘制决策树相关推荐

  1. python sklearn 绘制决策树模型的节点图

    绘制决策树的图片可以使用sklearn.tree.plot_tree这个方法 详情可以参考官方文档:https://scikit-learn.org/stable/modules/generated/ ...

  2. Python+matplotlib绘制散点图模拟心型图案

    推荐教材: <Python数据分析.挖掘与可视化>(慕课版)(ISBN:978-7-115-52361-7),董付国,人民邮电出版社,定价49.8元,2020年1月出版,2021年3月第6 ...

  3. python绘制决策树图片

    背景 w3cshool机器学习篇最后一个章节是决策树的简单入门教学,我在那里拷贝代码运行时报错,显示绘制不出决策树图片 思路 python编译报错无非三种,语法错误,没有装库,路径没对.w3cshoo ...

  4. 【机器学习实战】构建/绘制决策树(ID3/C4.5)

    近来想要整理一下机器学习实验的代码,将一些基本算法的过程重新整理实现,并完善注释. 一.构建决策树 1.计算信息熵calculate_entropy(dataset) 2.按某一特征划分数据集spli ...

  5. python中如何画出决策树_使用Python绘制决策树

    决策树为字典格式,示例如下: {'tearRate': {'reduced': 'no lenses', 'normal': {' astigmatic': {'yes': {' prescript' ...

  6. python绘制决策树

    前言:在使用python绘制决策树的时候,需要使用到matplotlib库,要想使用matplotlib库可以直接安装anaconda就可以了,anaconda中包含了许多的python科学计算库.在 ...

  7. 决策树(Decision Tree) | 绘制决策树

    01 起 在这篇文章中,我们讲解了如何训练决策树,然后我们得到了一个字典嵌套格式的决策树结果,这个结果不太直观,不能一眼看着这颗"树"的形状.分支.属性值等,怎么办呢? 本文就上文 ...

  8. matplotlib绘制图表,设置刻度标签、最大最小刻度、字体大小,label位置、刻度轴箭头等

    matplotlib绘制图表,设置刻度标签.最大最小刻度.字体大小,label位置.刻度轴箭头等 1. 效果图 2. 源码 2.1 仅使用普通轴ax + fontdict 源码 2.2 使用mpl设置 ...

  9. 使用KMeanCluster对多个区域进行聚类,并结合Matplotlib绘制中心点、最大最小距离点

    使用KMeanCluster对多个区域进行聚类,并结合Matplotlib绘制中心点.最大最小距离点 1. 效果图 2. 源码 2.1 原始数据--xq.txt 2.2 源码 参考 这篇博客将演示如何 ...

最新文章

  1. shiro 实现登录验证功能
  2. 破解世界性技术难题! GTS让分布式事务简单高效
  3. Python3文件操作:with...open的使用代码示例
  4. matlab colorbar采用对数,matlab colorbar的使用 | 學步園
  5. Chrome Version 19.0.1055.1 dev Flash Missing plug-in的修复
  6. 网友的有趣发现:冬天里,欧洲古建筑上的雕像都好像“生病了”
  7. 区块链六-Merkle Tree
  8. 如何减少silverlight XAP包的尺寸
  9. info index.php,真 · nginx配置php文件解析(PATH_INFO支持与index.php隐藏)
  10. 月球 dem_通过“月球灾害”应对错误信息的流行
  11. GDI+学习及代码总结之------画刷Brush .
  12. 【SQL】数据库模糊查询
  13. Google Earth Browser Plugin (谷歌 地球 浏览器 插件) 下载地址 5.0
  14. 主要几个浏览器的内核是什么
  15. Linux【实操篇】—— 进程管理、服务管理、软件包管理(rpm、yum)
  16. 看完还不会数据库优化,你来找我!
  17. 瑞星微RK3288开发板
  18. idea的git报错You have not concluded your merge
  19. 2020年数学建模国赛B题题目和解题思路
  20. IEEE754标准转换

热门文章

  1. 20172313 2017-2018-2 《程序设计与数据结构》第十周学习总结
  2. 手把手教你webpack3(3)入口(多入口)entry
  3. Android零基础入门第20节:CheckBox和RadioButton使用大全
  4. SQL SERVER 数据库邮件配置
  5. php 获取http headers
  6. Oracle 12c   归档模式更改
  7. SBO中流程控制功能的实现-SBO_SP_TransactionNotification
  8. IBM Webpshere6(WAS6) bug发现一例
  9. 黄金的商品属性,货币属性,金融属性
  10. how can you save more space at home?