在上一节我们已经学会决策树啦~
但是呢
结果是这样(字典形式):
{‘no surfacing’: {0: ‘no’, 1: {‘flippers’: {0: ‘no’, 1: ‘yes’}}}}
这节,我们把它绘制出来!
首先,我们先在Matplotlib上面练练手,画个丑东西
上代码:
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 )
def createPlot():
fig = plt.figure(1, facecolor='white')
fig.clf()
createPlot.ax1 = plt.subplot(111, frameon=False,)
plotNode('决策节点', (0.5, 0.1), (0.1, 0.5), decisionNode)
plotNode('叶节点', (0.8, 0.1), (0.3, 0.8), leafNode)
plt.show()
from pylab import mpl
mpl.rcParams['font.sans-serif'] = ['FangSong'] # 指定默认字体
mpl.rcParams['axes.unicode_minus'] = False # 解决保存图像是负号'-'显示为方块的问题
参考blog:https://blog.csdn.net/u010758410/article/details/71743225
ok,丑东西就这样画完了~
接下来,我们来画一棵完整的树,画之前我们要先确定
那就对应两个方法:
# 叶子节点数
def getNumLeafs(myTree):
print(myTree)
numLeafs = 0
firstStr = list(myTree.keys())[0] # 取出第一个键
secondDict = myTree[firstStr] # 取出键对应的值
for key in secondDict.keys():
if type(secondDict[key]).__name__ == 'dict': # 判断是否是字典类型,如'no'就是str类型,{'flippers': {0: {'head': {0: 'no', 1: 'yes'}}, 1: 'no'}}就还是dict类型
numLeafs += getNumLeafs(secondDict[key]) # dict类型的就继续递归
else:
numLeafs += 1
return numLeafs
# 树的深度
def getTreeDepth(myTree):
print(myTree)
maxDepth = 0
firstStr = list(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 # 如果我比maxDepth大,我就替代它
print(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]
递归确实比较绕,不小心就会晕了~ ~!
现在有了叶节点数和层数
好紧张~我要开始画了:
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)
def plotTree(myTree, parentPt, nodeTxt):
print(myTree)
numLeafs = getNumLeafs(myTree) # 计算树宽
depth = getTreeDepth(myTree) # 计算树高
firstStr = list(myTree.keys())[0]
cntrPt = (plotTree.xOff + (1.0 + float(numLeafs))/2.0/plotTree.totalW, plotTree.yOff)
print(cntrPt)
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
print(plotTree.xOff)
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)
#createPlot.ax1 = plt.subplot(111, frameon=False) #ticks for demo puropses
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()
结果:
上面画树的最绕的就是计算每个节点的位置,绕来绕去的然后我就晕了~
(1)对于高度,我们希望树能填充整个图像,于是,我们要得到树的深度depth,则可以设置高度的绘制步长为step_h = height/depth。由于绘制顺序是自上而下的(这里的自上而下是一个宏观上的看法,对于每个小的子树的搜寻顺序实际上是:根节点->左子树->根节点->右子树),故每一次递归都要y-step_h,当该次递归结束之后,需要y+step_h,回到递归的起始节点,继续判断递归(这个意思就是,该节点左子树递归,递归完毕回到该节点,开始递归右子树的过程)
(2)对于宽度,我们同样希望树能填充整个图像,于是,我们要得到树的叶子节点数目leafs,则可以设置宽度的绘制步长为step_w = width/leafs。根节点设置在中点位置,即(0.5,1)。接下来,每次递归的子树的根节点将位于其子树的中心位置(也就是该子树所有叶子节点构成宽度的中间)。由于绘制顺序是自左而右的,故我们设置xOff的初始值是-step_w0.5,每次递归都令xOff = xOff + step_w,如此,最左和最右的叶子节点与图边框相差距离为step_w0.5!
有个预测隐形眼镜类型的例子,其实就是换一下数据而已,重在掌握原理~