-
大小: 6KB文件類型: .py金幣: 1下載: 0 次發(fā)布日期: 2021-06-02
- 語言: Python
- 標(biāo)簽: python??機(jī)器學(xué)習(xí)??
資源簡介
treePlotter 繪制樹
機(jī)器學(xué)習(xí)matplotlib可能的繪制需要。哈哈哈哈 .... 積分太高啦
代碼片段和文件信息
‘‘‘
Created?on?Aug?14?2017
@author:?WordZzzz
‘‘‘
import?matplotlib.pyplot?as?plt
#定義文本框和箭頭格式
decisionNode?=?dict(boxstyle=“sawtooth“?fc=“0.8“)
leafNode?=?dict(boxstyle=“round4“?fc=“0.8“)
arrow_args?=?dict(arrowstyle=“<-“)
def?getNumLeafs(myTree):
“““
Function: 獲取葉節(jié)點(diǎn)的數(shù)目
Args: myTree:樹信息
Returns: numLeafs:葉節(jié)點(diǎn)的數(shù)目
“““
#初始化葉節(jié)點(diǎn)數(shù)目
numLeafs?=?0
#第一個關(guān)鍵字為第一次劃分?jǐn)?shù)據(jù)集的類別標(biāo)簽,附帶的取值表示子節(jié)點(diǎn)的取值
firstStr?=?list(myTree.keys())[0]
#新的樹,相當(dāng)于脫了一層皮
secondDict?=?myTree[firstStr]
for?key?in?secondDict.keys():
#判斷子節(jié)點(diǎn)是否為字典類型
if?type(secondDict[key]).__name__==‘dict‘:
#是的話表明該節(jié)點(diǎn)也是一個判斷節(jié)點(diǎn),遞歸調(diào)用getNumLeafs()函數(shù)
numLeafs?+=?getNumLeafs(secondDict[key])
else:
#不是的話表明到頭了,賦值累加1
numLeafs?+=?1
#返回葉節(jié)點(diǎn)數(shù)目
return?numLeafs
def?getTreeDepth(myTree):
“““
Function: 獲取樹的層數(shù)
Args: myTree:樹信息
Returns: maxDepth:最大層數(shù)
“““
#初始化最大層數(shù)
maxDepth?=?0
#第一個關(guān)鍵字為第一次劃分?jǐn)?shù)據(jù)集的類別標(biāo)簽,附帶的取值表示子節(jié)點(diǎn)的取值
firstStr?=?list(myTree.keys())[0]
#新的樹,相當(dāng)于脫了一層皮
secondDict?=?myTree[firstStr]
for?key?in?secondDict.keys():
#判斷子節(jié)點(diǎn)是否為字典類型
if?type(secondDict[key]).__name__==‘dict‘:
#是的話表明該節(jié)點(diǎn)也是一個判斷節(jié)點(diǎn),遞歸調(diào)用getTreeDepth()函數(shù)
thisDepth?=?1?+?getTreeDepth(secondDict[key])
else:
#不是的話表明到頭了,此時(shí)賦值為1
thisDepth?=?1
if?thisDepth?>?maxDepth:?maxDepth?=?thisDepth
#返回最大層數(shù)
return?maxDepth
def?plotNode(nodeTxt?centerPt?parentPt?nodeType):
“““
Function: 繪制帶箭頭的注解
Args: nodeTxt:文本注解
centerPt:箭頭終點(diǎn)坐標(biāo)
parentPt:箭頭起始坐標(biāo)
nodeType:文本框類型
Returns: 無
“““
#在全局變量createPlot.ax1中繪圖
createPlot.ax1.annotate(nodeTxt?xy=parentPt??xycoords=‘a(chǎn)xes?fraction‘
?xytext=centerPt?textcoords=‘a(chǎn)xes?fraction‘
?va=“center“?ha=“center“?bbox=nodeType?arrowprops=arrow_args?)
#在全局變量createPlot0.ax1中繪圖
# createPlot0.ax1.annotate(nodeTxt?xy=parentPt??xycoords=‘a(chǎn)xes?fraction‘
# ?xytext=centerPt?textcoords=‘a(chǎn)xes?fraction‘
# ?va=“center“?ha=“center“?bbox=nodeType?arrowprops=arrow_args?)
def?plotMidText(cntrPt?parentPt?txtString):
“““
Function: 在父子節(jié)點(diǎn)間填充文本信息
Args: cntrPt:樹信息
parentPt:父節(jié)點(diǎn)坐標(biāo)
txtString:文本注解
Returns: 無
“““
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):#if?the?first?key?tells?you?what?feat?was?split?on
“““
Function: 創(chuàng)建數(shù)據(jù)集和標(biāo)簽
Args: myTree:樹信息
parentPt:箭頭起始坐標(biāo)
nodeTxt:文本注解
Returns: 無
“““
#計(jì)算樹的寬
numLeafs?=?getNumLeafs(myTree)??#this?determines?the?x?width?of
- 上一篇:天貓?jiān)u論爬蟲
- 下一篇:python圖像處理三維重建所有代碼
評論
共有 條評論