《機器學習實戰》第三章 3.2在python 中使用matplotlib註解繪製樹形圖
阿新 • • 發佈:2019-02-07
《機器學習實戰》系列部落格主要是實現並理解書中的程式碼,相當於讀書筆記了。畢竟實戰不能光看書。動手就能遇到許多奇奇怪怪的問題。博文比較粗糙,需結合書本。博主邊查邊學,水平有限,有問題的地方評論區請多指教。書中的程式碼和資料,網上有很多請自行下載。
3.2.1Matplotlib註解
註解工具 annotations
這段程式碼有點煩瑣,出現很多繪圖函式,可以檢視matplotlib 文件
使用文字註解繪製樹節點
#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 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()
命令列輸入
>>> import treePlotter
>>> treePlotter.createPlot()
3.2.2 構造註解樹
樹在python中用巢狀字典儲存
例 :>>> myTree
{‘no surfacing’: {0: ‘no’, 1: {‘flippers’: {0: ‘no’, 1: ‘yes’}}}}
鍵值是字典則是判斷結點,否則是葉子節點
獲取葉子結點數和層數
def getNumLeafs(myTree):
numLeafs = 0
firstStr = myTree.keys()[0] #字典的第一個鍵,即樹的一個結點
secondDict = myTree[firstStr] #這個鍵的值,即該結點的所有子樹
for key in secondDict.keys():
if type(secondDict[key]).__name__=='dict':#test to see if the nodes are dictonaires, if not they are leaf nodes
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
函式retrieveTree 建立兩棵樹,用來測試
>>> import treePlotter
>>> mytree = treePlotter.retrieveTree(0)
>>> treePlotter.getNumLeafs(mytree)
3
>>> treePlotter.getTreeDepth(mytree)
2
PlotTree 函式
感覺葉子橫座標放的位置還沒理解的很清楚
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) #沒有用到這個變數
firstStr = myTree.keys()[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)
>>> import treePlotter
>>> mytree = treePlotter.retrieveTree(0)
>>> treePlotter.getNumLeafs(mytree)
3
>>> treePlotter.getTreeDepth(mytree)
2
>>> treePlotter.createPlot(mytree)