python中如何画出决策树_使用Python绘制决策树
決策樹為字典格式,示例如下:
{'tearRate': {'reduced': 'no lenses', 'normal': {' astigmatic': {'yes': {' prescript': {'hyper': {'age': {'pre': 'no lenses', 'presbyopic': 'no lenses', 'young': 'hard'}}, 'myope': 'hard'}}, 'no': {'age': {'pre': 'soft', 'presbyopic': {' prescript': {'hyper': 'soft', 'myope': 'no lenses'}}, 'young': 'soft'}}}}}}
繪制決策樹代碼
import matplotlib.pyplot as plt
def getNumLeafs(myTree):
# 初始化樹的葉子節點個數
numLeafs = 0
# myTree.keys()獲取樹的非葉子節點'no surfacing'和'flippers'
# list(myTree.keys())[0]獲取第一個鍵名'no surfacing'
firstStr = list(myTree.keys())[0]
# 通過鍵名獲取與之對應的值,即{0: 'no', 1: {'flippers': {0: 'no', 1: 'yes'}}}
secondDict = myTree[firstStr]
# 遍歷樹,secondDict.keys()獲取所有的鍵
for key in secondDict.keys():
# 判斷鍵是否為字典,鍵名1和其值就組成了一個字典,如果是字典則通過遞歸繼續遍歷,尋找葉子節點
if type(secondDict[key]).__name__ == 'dict':
numLeafs += getNumLeafs(secondDict[key])
# 如果不是字典,則葉子結點的數目就加1
else:
numLeafs += 1
# 返回葉子節點的數目
return numLeafs
def getTreeDepth(myTree):
# 初始化樹的深度
maxDepth = 0
# 獲取樹的第一個鍵名
firstStr = list(myTree.keys())[0]
# 獲取鍵名所對應的值
secondDict = myTree[firstStr]
# 遍歷樹
for key in secondDict.keys():
# 如果獲取的鍵是字典,樹的深度加1
if type(secondDict[key]).__name__ == 'dict':
thisDepth = 1 + getTreeDepth(secondDict[key])
else:
thisDepth = 1
# 去深度的最大值
if thisDepth > maxDepth: maxDepth = thisDepth
# 返回樹的深度
return maxDepth
# 繪圖相關參數的設置
def plotNode(nodeTxt, centerPt, parentPt, nodeType):
# annotate函數是為繪制圖上指定的數據點xy添加一個nodeTxt注釋
# nodeTxt是給數據點xy添加一個注釋,xy為數據點的開始繪制的坐標,位于節點的中間位置
# xycoords設置指定點xy的坐標類型,xytext為注釋的中間點坐標,textcoords設置注釋點坐標樣式
# bbox設置裝注釋盒子的樣式,arrowprops設置箭頭的樣式
'''
figure points:表示坐標原點在圖的左下角的數據點
figure pixels:表示坐標原點在圖的左下角的像素點
figure fraction:此時取值是小數,范圍是([0,1],[0,1]),在圖的左下角時xy是(0,0),最右上角是(1,1)
其他位置是按相對圖的寬高的比例取最小值
axes points : 表示坐標原點在圖中坐標的左下角的數據點
axes pixels : 表示坐標原點在圖中坐標的左下角的像素點
axes fraction : 與figure fraction類似,只不過相對于圖的位置改成是相對于坐標軸的位置
'''
createPlot.ax1.annotate(nodeTxt, xy=parentPt, \
xycoords='axes fraction', xytext=centerPt, textcoords='axes fraction', \
va="center", ha="center", bbox=nodeType, arrowprops=arrow_args)
# 繪制線中間的文字(0和1)的繪制
def plotMidText(cntrPt, parentPt, txtString):
xMid = (parentPt[0] - cntrPt[0]) / 2.0 + cntrPt[0] # 計算文字的x坐標
yMid = (parentPt[1] - cntrPt[1]) / 2.0 + cntrPt[1] # 計算文字的y坐標
createPlot.ax1.text(xMid, yMid, txtString)
# 繪制樹
def plotTree(myTree, parentPt, nodeTxt):
# 獲取樹的葉子節點
numLeafs = getNumLeafs(myTree)
# 獲取樹的深度
depth = getTreeDepth(myTree)
# firstStr = myTree.keys()[0]
# 獲取第一個鍵名
firstStr = list(myTree.keys())[0]
# 計算子節點的坐標
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]
# 計算節點y方向上的偏移量,根據樹的深度
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:
# 更新x的偏移量,每個葉子結點x軸方向上的距離為 1/plotTree.totalW
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
# 繪制決策樹,inTree的格式為{'no surfacing': {0: 'no', 1: {'flippers': {0: 'no', 1: 'yes'}}}}
def createPlot(inTree):
# 新建一個figure設置背景顏色為白色
fig = plt.figure(1, facecolor='white')
# 清除figure
fig.clf()
axprops = dict(xticks=[], yticks=[])
# 創建一個1行1列1個figure,并把網格里面的第一個figure的Axes實例返回給ax1作為函數createPlot()
# 的屬性,這個屬性ax1相當于一個全局變量,可以給plotNode函數使用
createPlot.ax1 = plt.subplot(111, frameon=False, **axprops)
# 獲取樹的葉子節點
plotTree.totalW = float(getNumLeafs(inTree))
# 獲取樹的深度
plotTree.totalD = float(getTreeDepth(inTree))
# 節點的x軸的偏移量為-1/plotTree.totlaW/2,1為x軸的長度,除以2保證每一個節點的x軸之間的距離為1/plotTree.totlaW*2
plotTree.xoff = -0.5 / plotTree.totalW
plotTree.yoff = 1.0
plotTree(inTree, (0.5, 1.0), '')
plt.show()
運行代碼
# 設置畫節點用的盒子的樣式
decisionNode = dict(boxstyle="sawtooth", fc="0.8")
leafNode = dict(boxstyle="round4", fc="0.8")
# 設置畫箭頭的樣式
arrow_args = dict(arrowstyle="
tree_dict = {'tearRate': {'reduced': 'no lenses', 'normal': {' astigmatic': {'yes': {' prescript': {'hyper': {'age': {'pre': 'no lenses', 'presbyopic': 'no lenses', 'young': 'hard'}}, 'myope': 'hard'}}, 'no': {'age': {'pre': 'soft', 'presbyopic': {' prescript': {'hyper': 'soft', 'myope': 'no lenses'}}, 'young': 'soft'}}}}}}
createPlot(tree_dict)
效果圖
決策樹構建示例
決策樹實戰——預測隱形眼睛類型
總結
以上是生活随笔為你收集整理的python中如何画出决策树_使用Python绘制决策树的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 自考计算机网络应用,自考计算机网络原理总
- 下一篇: jenkins 集成coding实现自动