机器学习实战-决策树-画图2
- 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()
- 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=list(myTree.keys())[0]
- cntrPt=(plotTree.xoff+(1+float(numLeafs))/2.0/plotTree.totalW,plotTree.yoff)
- #此处子节点的off推导公式有点复杂,有知道怎么推的求告知
- 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])==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#如果没有这条语句将会造成绘制完一个决策节点之后不会返回至上一父节点位置
- myTree=retrieveTree(0)
这是画图的最后一部分代码了,明天就开始做实例了
创建图层界面还好理解,画图也好理解,但是具体到 xoff 时就出现推导困难了,慢慢调,找出计算子节点 cntrPt 这个东西时,off的计算需要plotTree.xoff+(1+float(numLeafs))/2.0/plotTree.totalW
这样计算。
第一个函数createPlot是一个建立图层界面以及画图的函数,但是具体的画图步骤又在plotTree函数中,其中plotTree需要引用plotMidText函数来画出连接上的key值
plotTree.totalW这种新奇的用法,这样我就能在createTree函数里调用plotTree的参数了,而不需要做出一个全局变量