決策樹構建與深度節點數簡單例子
1、構建treePlotter.py
#coding:utf-8 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.annotate(nodeTxt, xy=parentPt, xycoords='axes fraction', xytext=centerPt, textcoords='axes fraction', va="center", ha="center", bbox=nodeType, arrowprops=arrow_args ) def createSimplePlot(): 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() def getNumLeafs(myTree): numLeafs = 0 firstSides = list(myTree.keys()) firstStr = firstSides[0] secondDict = myTree[firstStr] for key in secondDict.keys(): if type(secondDict[key]).__name__ == 'dict': numLeafs += getNumLeafs(secondDict[key]) else: numLeafs += 1 return numLeafs def getTreeDepth(myTree): maxDepth = 0 firstSides = list(myTree.keys()) firstStr = firstSides[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 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) plotTree.totalW = float(getNumLeafs(inTree)) #全域性變數寬度 = 葉子數 plotTree.totalD = float(getTreeDepth(inTree)) #全域性變數高度 = 深度 #圖形的大小是0-1 ,0-1 plotTree.xOff = -0.5/plotTree.totalW; #例如繪製3個葉子結點,座標應為1/3,2/3,3/3 #但這樣會使整個圖形偏右因此初始的,將x值向左移一點。 plotTree.yOff = 1.0; plotTree(inTree, (0.5,1.0), '') plt.show() def plotTree(myTree, parentPt, nodeTxt): numLeafs = getNumLeafs(myTree) #當前樹的葉子數 depth = getTreeDepth(myTree) #沒有用到這個變數 firstSides = list(myTree.keys()) firstStr = firstSides[0] #cntrPt文字中心點 parentPt 指向文字中心的點 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 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 retrieveTree(i): listOfTrees =[{'no surfacing': {0:{'flippers': {0: 'no', 1: 'yes'}}, 1: {'flippers': {0: 'no', 1: 'yes'}}, 2:{'flippers': {0: 'no', 1: 'yes'}}}}, {'no surfacing': {0: 'no', 1: {'flippers': {0: {'head': {0: 'no', 1: 'yes'}}, 1: 'no'}}}} ] return listOfTrees[i]
2、構建Treetest.py
import treePlotter
#treePlotter.createSimplePlot()
mytree= {'no surfacing': {0: 'no', 1: {'flippers': {0: 'no', 1: 'yes'}}}}
#mytree = treePlotter.retrieveTree(0)
print (treePlotter.getNumLeafs(mytree))
print (treePlotter.getTreeDepth(mytree))
treePlotter.createPlot(mytree)