《机器学习实战》第三章 3.2 在Python中使用Matplotlib注解绘制树形图

xiaoxiao2021-02-28  71

《机器学习实战》第三章 3.2 在Python中使用Matplotlib注解绘制树形图

自己按照树上的代码敲了一遍(Spyder),调试之后可以使用,向大家分享一下,另外,有好多的注解,希望对大家有帮助。 代码源代码 # -*- coding: utf-8 -*- """ Created on Mon Dec 18 10:53:31 2017 @author: XU LI """ #使用Matplotlib绘制树形图----注解工具annotations #博客http://blog.csdn.net/csdn_lzw/article/details/56835176 #使用文本注解绘制树节点 import matplotlib.pyplot as plt #定义决策树决策结果的属性,用字典来定义 #下面的字典定义也可写作 decisionNode={boxstyle:'sawtooth',fc:'0.8'} #boxstyle为文本框的类型,sawtooth是锯齿形,fc是边框线粗细 decisionNode = dict(boxstyle="sawtooth", fc="0.8") leafNode = dict(boxstyle="round4", fc="0.8") arrow_args = dict(arrowstyle="<-") def plotNode(nodeTxt, centerPt, parentPt, nodeType): # annotate是关于一个数据点的文本 # nodeTxt为要显示的文本,centerPt为文本的中心点,箭头所在的点,parentPt为指向文本的点 #createPlot.ax1定义一个绘图区 createPlot.ax1.annotate(nodeTxt, xy=parentPt, xycoords='axes fraction', xytext=centerPt, textcoords='axes fraction', va="center", ha="center", bbox=nodeType, arrowprops=arrow_args ) def createPlot(): fig = plt.figure(1,facecolor='white') # 定义一个画布,背景为白色 fig.clf() # 把画布清空 # createPlot.ax1为全局变量,绘制图像的句柄,subplot为定义了一个绘图, #111表示figure中的图有1行1列,即1个,最后的1代表第一个图 # frameon表示是否绘制坐标轴矩形 createPlot.ax1 = plt.subplot(111,frameon=False) plotNode('a decision node',(0.5,0.1),(0.1,0.5),decisionNode) plotNode('a leaf node',(0.8,0.1),(0.3,0.8),leafNode) plt.show() #确定x,y轴的长度来放置所有的树节点 #获取叶节点的数目和树的层数 def getNumLeafs(myTree): numLeafs = 0 firstStr = myTree.keys()[0] #字典的第一个键,即树的一个结点 secondDict = myTree[firstStr] #这个键的值,即该结点的所有子树 for key in secondDict.keys(): if type(secondDict[key]).__name__=='dict': #使用type()判断子节点是否是字典类型 numLeafs += getNumLeafs(secondDict[key]) else : numLeafs += 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]) else : thisDepth = 1 if thisDepth > maxDepth: maxDepth = thisDepth return maxDepth #输出预先存储的树信息 def retrieveTree(i): listOfTrees = [{'no surfacing':{0:'no',1:{'flippers':{0:'no',1:'yes'}}}}, {'no surfacing':{0:'no',1:{'flippers':{0:{'head':{0:'no', 1:'yes'}},1:'no'}}}}] #定义了两个字典 return listOfTrees[i] #plotTree 函数 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) def plotTree(myTree,parentPt,nodeTxt): #递归函数,计算树的宽和高 numLeafs = getNumLeafs(myTree) #当前树的叶子数 depth = getTreeDepth(myTree) #没有用到这个变量 firstStr = myTree.keys()[0] cntrpt = (plotTree.x0ff + (1.0 + float(numLeafs))/2.0/plotTree.totalW,plotTree.y0ff) #cntrPt文本中心点 parentPt指向文本中心的点 plotMidText(cntrpt,parentPt,nodeTxt) #画分支上的键 plotNode(firstStr,cntrpt,parentPt,decisionNode) secondDict = myTree[firstStr] plotTree.y0ff = plotTree.y0ff - 1.0/plotTree.totalD #从上往下画,依次递减y的坐标值 for key in secondDict.keys(): if type(secondDict[key]).__name__=='dict': #如果是字典则是一个判断(内部)结点 plotTree(secondDict[key],cntrpt,str(key)) else: plotTree.x0ff = plotTree.x0ff + 1.0/plotTree.totalW plotNode(secondDict[key],(plotTree.x0ff,plotTree.y0ff),cntrpt, leafNode) plotMidText((plotTree.x0ff,plotTree.y0ff),cntrpt,str(key)) plotTree.y0ff = plotTree.y0ff + 1.0/plotTree.totalD def createPlot(inTree): #创建绘图区,计算树形图的全局尺寸,并调用递归函数plotTree() 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.x0ff = -0.5/plotTree.totalW;#例如绘制3个叶子结点,坐标应为1/3,2/3,3/3 #但这样会使整个图形偏右因此初始的,将x值向左移一点。 plotTree.y0ff = 1.0; plotTree(inTree, (0.5,1.0), '') plt.show()

3.结果分析代码

# -*- coding: utf-8 -*- """ Created on Sat Oct 28 20:52:14 2017 @author: XU LI """ myData,labels = createDataSet() print myData print calcShannonEnt(myData) print'---------------------------------' print splitDataSet (myData,0,1) print splitDataSet (myData,0,0) print splitDataSet (myData,1,1) print splitDataSet (myData,1,0) print'---------------------------------' myData,labels = createDataSet() print myData print '第', chooseBestFeatureToSplit(myData), print '个特征是最好的用于划分数据集的特征' print'---------------------------------' myData,labels = createDataSet() myTree = createTree(myData,labels) print 'myTree=',myTree print'---------------------------------' #treePlotter.createPlot() print'---------------------------------' print treePlotter.retrieveTree(1) myTree = treePlotter.retrieveTree(0) print myTree print treePlotter.getNumLeafs(myTree) print treePlotter.getTreeDepth(myTree) print'---------------------------------' myTree = retrieveTree(0) createPlot(myTree)

4.结果

转载请注明原文地址: https://www.6miu.com/read-1950367.html

最新回复(0)