机器学习实战-决策树-画图2

  1. def createPlot(inTree):  
  2.     fig=plt.figure(1,facecolor='white')  
  3.     fig.clf()  
  4.     axprops=dict(xticks=[],yticks=[])  
  5.     createPlot.ax1=plt.subplot(111,frameon=False,**axprops)  
  6.     plotTree.totalW=float(getNumLeafs(inTree))  
  7.     plotTree.totalD=float(getTreeDepth(inTree))  
  8.     plotTree.xoff=-0.5/plotTree.totalW  
  9.     plotTree.yoff=1.0  
  10.     plotTree(inTree,(0.5,1.0),'')  
  11.     plt.show()  
  12.     
  13. def plotMidText(cntrPt,parentPt,txtString):  
  14.     xMid=(parentPt[0]-cntrPt[0])/2.0+cntrPt[0]  
  15.     yMid=(parentPt[1]-cntrPt[1])/2.0+cntrPt[1]  
  16.     createPlot.ax1.text(xMid,yMid,txtString)  
  17.     
  18. def plotTree(myTree,parentPt,nodeTxt):  
  19.     numLeafs=getNumLeafs(myTree)  
  20.     depth=getTreeDepth(myTree)  
  21.     firstStr=list(myTree.keys())[0]  
  22.     cntrPt=(plotTree.xoff+(1+float(numLeafs))/2.0/plotTree.totalW,plotTree.yoff)  
  23. #此处子节点的off推导公式有点复杂,有知道怎么推的求告知  
  24.     plotMidText(cntrPt,parentPt,nodeTxt)  
  25.     plotNode(firstStr,cntrPt,parentPt,decisionNode)  
  26.     secondDict=myTree[firstStr]  
  27.     plotTree.yoff=plotTree.yoff-1.0/plotTree.totalD  
  28.     for key in secondDict.keys():  
  29.         if type(secondDict[key])==dict:  
  30.                 
  31.             plotTree(secondDict[key],cntrPt,str(key))  
  32.         else:  
  33.             plotTree.xoff=plotTree.xoff+1.0/plotTree.totalW  
  34.             plotNode(secondDict[key],(plotTree.xoff,plotTree.yoff),cntrPt,leafNode)  
  35.             plotMidText((plotTree.xoff,plotTree.yoff),cntrPt,str(key))  
  36.     plotTree.yoff=plotTree.yoff+1.0/plotTree.totalD#如果没有这条语句将会造成绘制完一个决策节点之后不会返回至上一父节点位置  
  37.     
  38. myTree=retrieveTree(0)

这是画图的最后一部分代码了,明天就开始做实例了

创建图层界面还好理解,画图也好理解,但是具体到 xoff 时就出现推导困难了,慢慢调,找出计算子节点 cntrPt 这个东西时,off的计算需要plotTree.xoff+(1+float(numLeafs))/2.0/plotTree.totalW

这样计算。

第一个函数createPlot是一个建立图层界面以及画图的函数,但是具体的画图步骤又在plotTree函数中,其中plotTree需要引用plotMidText函数来画出连接上的key

 

plotTree.totalW这种新奇的用法,这样我就能在createTree函数里调用plotTree的参数了,而不需要做出一个全局变量

posted @ 2018-12-06 23:46  天字三号房  阅读(429)  评论(0编辑  收藏  举报