正方形代表判斷模塊(decision block) ,橢圓代表終止模塊(terminating block),表示已經(jīng)得到結(jié)論,可以終止運(yùn)動(dòng)。
決策樹的優(yōu)勢(shì)在于數(shù)據(jù)形式容易理解。
決策樹的很多任務(wù)都是為了數(shù)據(jù)中所蘊(yùn)含的知識(shí)信息。
決策樹可以使用不熟悉的數(shù)據(jù)集合,并從中提取出一系列規(guī)則,機(jī)器學(xué)習(xí)算法最終將使用這些機(jī)器從數(shù)據(jù)集中創(chuàng)造的規(guī)則。
3.1決策樹的構(gòu)造
優(yōu)點(diǎn):計(jì)算復(fù)雜度不高,輸出結(jié)果易于理解,對(duì)中間值的缺失不敏感,可以處理不相關(guān)特征數(shù)據(jù)。
缺點(diǎn):可能會(huì)產(chǎn)生過(guò)度匹配的問(wèn)題。
適用數(shù)據(jù)類型:數(shù)值型和標(biāo)稱型。
1.先討論數(shù)學(xué)上如何使用信息論劃分?jǐn)?shù)據(jù)集;
2.編寫代碼將理論應(yīng)用到具體的數(shù)據(jù)集上;
3.編寫代碼構(gòu)建決策樹;
創(chuàng)建分支的偽代碼函數(shù)createBranch()
檢測(cè)數(shù)據(jù)集中的每個(gè)子項(xiàng)是否屬于同一分類:
If so return 類標(biāo)簽 :
Else
尋找劃分?jǐn)?shù)據(jù)集的最好特征
劃分?jǐn)?shù)據(jù)集
創(chuàng)建分支節(jié)點(diǎn)
for 每個(gè)劃分的子集
調(diào)用函數(shù)createBranch 并增加返回結(jié)果到分支節(jié)點(diǎn)中
return 分子節(jié)點(diǎn)
上面的偽代碼createBranch是一個(gè)遞歸函數(shù),在倒數(shù)第二行直接調(diào)用它子集
決策樹一般流程
收集數(shù)據(jù):可以直接使用任何方法
準(zhǔn)備數(shù)據(jù):構(gòu)造算法只適用于標(biāo)稱型數(shù)據(jù),因此數(shù)值型數(shù)據(jù)必須離散化。
分析數(shù)據(jù):可以使用任何方法,構(gòu)造完樹以后,我們應(yīng)該檢查圖形是否符合預(yù)期。
訓(xùn)練算法:構(gòu)造數(shù)的數(shù)據(jù)結(jié)構(gòu)。
測(cè)試算法:使用經(jīng)驗(yàn)樹計(jì)算錯(cuò)誤概率
使用算法:此步驟可以適應(yīng)于任何監(jiān)督學(xué)習(xí)算法,而使用決策樹可以更好的理解數(shù)據(jù)的內(nèi)在含義。
本次我們使用ID3算法來(lái)劃分?jǐn)?shù)據(jù)集。每次劃分?jǐn)?shù)據(jù)集的時(shí)我們只選取一個(gè)特征值。
決策樹學(xué)習(xí)采用的是自頂向下的遞歸方法,其基本思想是以信息熵為度量構(gòu)造一棵熵值下降最快的樹,到葉子節(jié)點(diǎn)處的熵值為零,此時(shí)每個(gè)葉節(jié)點(diǎn)中的實(shí)例都屬于同一類。
3.1.1 信息增益
劃分?jǐn)?shù)據(jù)集的大原則是 :將無(wú)序的數(shù)據(jù)變得有序。
組織雜亂無(wú)章數(shù)據(jù)的一種方法就是使用信息論度量信息,信息論是量化處理信息的分支科學(xué)。
在劃分?jǐn)?shù)據(jù)集之前之后的信息發(fā)生的變化稱之為信息增益,知道如何計(jì)算信息增益,我們就可以計(jì)算每個(gè)特征的值劃分?jǐn)?shù)據(jù)集獲得的信息增益,獲得信息增益最高的特征就是最好的選擇。
集合信息的度量方式稱之為 香農(nóng)熵。
熵
熵是信息論中的概念,用來(lái)表示集合的無(wú)序程度,熵越大表示集合越混亂,反之則表示集合越有序。熵的計(jì)算公式為:
E = -P * log2P
熵定義為信息的期望值。那什么是信息呢?如果待分類的事務(wù)可能劃分在多個(gè)分類之中,負(fù)荷xi的信息定義為:
其中,p(xi)是選擇分類的概率。
為了計(jì)算熵,我們需要計(jì)算所有類別的
其中n是分類的數(shù)目。
接下來(lái)我們將使用pythoon計(jì)算信息熵,去度量數(shù)據(jù)集的無(wú)序程度,創(chuàng)建名為trees.py的文件。
from math import log
def calcShannonEnt(dataSet):
#計(jì)算數(shù)據(jù)集中實(shí)例的總數(shù)
numEntries = len(dataSet)
#創(chuàng)建一個(gè)數(shù)據(jù)字典
labelCounts = {}
for featVec in dataSet:
#取鍵值最后一列的數(shù)值的最后一個(gè)字符串
currentLabel = featVec[-1]
#鍵值不存在就使當(dāng)前鍵加入字典
if currentLabel not in labelCounts.keys():
labelCounts[currentLabel] = 0
labelCounts[currentLabel] += 1
shannonEnt = 0.0
for key in labelCounts:
prob = float(labelCounts[key])/numEntries
#以2為底求對(duì)數(shù)
shannonEnt -= prob * log(prob,2)
return shannonEnt
我們輸入 一個(gè)數(shù)據(jù)來(lái)測(cè)試一下。
In [65]: import trees
In [67]: reload(trees)
Out[67]: <module 'trees' from 'trees.py'>
In [69]: def createDatSet():
...: dataSet = [[1,1,'yes'],
...: [1,1,'yes'],
...: [1,0,'no'],
...: [0,1,'no'],
...: [0,1,'no']]
...: labels = ['no surfacing','flippers']
...: return dataSet,labels
...:
In [70]: myDat,labels = trees.createDatSet()
In [71]: myDat
Out[71]: [[1, 1, 'yes'], [1, 1, 'yes'], [1, 0, 'no'], [0, 1, 'no'], [0, 1, 'no']]
In [72]: trees.calcShannonEnt(myDat)
Out[72]: 0.9709505944546686
熵越高,混合的數(shù)據(jù)就越多。
我們可以向數(shù)據(jù)集中添加更多的分類,以此來(lái)觀測(cè)熵是如何變化的。
In [95]: myDat[0][-1]='maybe'
In [96]: myDat
Out[96]: [[1, 1, 'maybe'], [1, 1, 'yes'], [1, 0, 'no'], [0, 1, 'no'], [0, 1, 'no']]
In [97]: trees.calcShannonEnt(myDat)
Out[97]: 1.3709505944546687
3.1.2 劃分?jǐn)?shù)據(jù)集
分類算法除了要度量數(shù)據(jù)集的無(wú)序程度(信息熵),還需要?jiǎng)澐謹(jǐn)?shù)據(jù)集,度量劃分?jǐn)?shù)據(jù)集的熵。以便于判斷當(dāng)前是否正確劃分了數(shù)據(jù)集。
我們隊(duì)每個(gè)特征劃分一次數(shù)據(jù)集的結(jié)果計(jì)算一次信息熵,然后去判斷按照哪個(gè)特征劃分?jǐn)?shù)據(jù)集是最好的劃分方式。
代碼 : 按照給定的特征劃分?jǐn)?shù)據(jù)集
#dataSet:待劃分的數(shù)據(jù)集
#axis劃分?jǐn)?shù)據(jù)集的特征
#特征的返回值
def splitDataSet(dataSet,axis,value):
#創(chuàng)建新的list對(duì)象
retDataSet=[]
for featVec in dataSet:
if featVec[axis] == value:
reducedFeatVec = featVec[:axis]
reducedFeatVec.extend(featVec[axis+1:])
retDataSet.append(reducedFeatVec)
return retDataSet
上述代碼append和extend方法,區(qū)別如下:
In [18]: a = [1,2,3]
In [19]: b = [4,5,6]
In [20]: a.append(b)
In [21]: a
Out[21]: [1, 2, 3, [4, 5, 6]]
In [22]: a = [1,2,3]
In [23]: b = [4,5,6]
In [24]: a.extend(b)
In [25]: a
Out[25]: [1, 2, 3, 4, 5, 6]
測(cè)試一下劃分?jǐn)?shù)據(jù)集的代碼:
In [35]: reload(trees)
Out[35]: <module 'trees' from 'trees.py'>
In [36]: myDat,labels = trees.createDatSet()
In [37]: myDat
Out[37]: [[1, 1, 'yes'], [1, 1, 'yes'], [1, 0, 'no'], [0, 1, 'no'], [0, 1, 'no']]
In [38]: trees.splitDataSet(myDat,0,1)
Out[38]: [[1, 'yes'], [1, 'yes'], [0, 'no']]
In [39]: trees.splitDataSet(myDat,0,0)
Out[39]: [[1, 'no'], [1, 'no']]
記下來(lái)我們會(huì)遍歷整個(gè)數(shù)據(jù)集,循環(huán)計(jì)算香農(nóng)熵和splitDataSet()函數(shù),找到最好的特征劃分方式。熵計(jì)算會(huì)得出如何劃分?jǐn)?shù)據(jù)集是最好的數(shù)據(jù)組織方式。
def choooseBestFeatureToSplit(dataSet):
numFeatures = len(dataSet[0]) -1
baseEntropy = calcShannonEnt(dataSet)
bestInfoGain = 0.0
beatFeature =-1
for i in range(numFeatures):
#創(chuàng)建唯一的分類標(biāo)簽列表
#取dataSet的第i個(gè)數(shù)據(jù)的第i個(gè)數(shù)據(jù),并寫入列表
featList = [example[i] for example in dataSet]
#將列表的數(shù)據(jù)集合在一起,并去重
uniqueVals = set(featList)
newEntropy = 0.0
#計(jì)算每種劃分方式的信息熵
for value in uniqueVals:
subDataSet = splitDataSet(dataSet,i,value)
prob = len(subDataSet)/float(len(dataSet))
newEntropy += prob * calcShannonEnt(subDataSet)
infoGain = baseEntropy - newEntropy
#計(jì)算好信息熵增益
if (infoGain > bestInfoGain):
bestInfoGain = infoGain
bestFeature = i
return bestFeature
上述代碼實(shí)現(xiàn)選取特征,劃分?jǐn)?shù)據(jù)集,計(jì)算出最好的劃分?jǐn)?shù)據(jù)集的特征。
在函數(shù)的調(diào)用的數(shù)據(jù)中滿足一定的要求:
(1) 數(shù)據(jù)必須是一種由列表元素組成的列表,且所有的列表元素具有相同的數(shù)據(jù)長(zhǎng)度。
(2) 數(shù)據(jù)最后一列或每個(gè)實(shí)例的最后一個(gè)元素是當(dāng)前實(shí)例的類別標(biāo)簽。
測(cè)試代碼:
In [179]: reload(trees)
In [179]: Out[179]: <module 'trees' from 'trees.py'>
In [180]: trees.choooseBestFeatureToSplit(myDat)
Out[180]: 0
In [181]: myDat
Out[181]: [[1, 1, 'yes'], [1, 1, 'yes'], [1, 0, 'no'], [0, 1, 'no'], [0, 1, 'no']]
根據(jù)上述的結(jié)果,第0個(gè)特征就是最好的用于劃分?jǐn)?shù)據(jù)集的特征。
3.1.3 遞歸構(gòu)建決策樹
目前我們已經(jīng)給出了從數(shù)據(jù)集構(gòu)造決策樹算法所需要的子功能模塊,工作原理如下:
得到原始數(shù)據(jù)集,然后基于最好的屬性值劃分?jǐn)?shù)據(jù)集,由于特征值可能多于兩個(gè),因此可能存在大于兩個(gè)分支的數(shù)據(jù)集劃分。第一次劃分之后,數(shù)據(jù)將被鄉(xiāng)下傳遞到樹分支的下一個(gè)節(jié)點(diǎn),在這個(gè)節(jié)點(diǎn)上,可以再次劃分?jǐn)?shù)據(jù)。因此我們可以使用遞歸的原理來(lái)處理數(shù)據(jù)。
遞歸結(jié)束的條件是:程序遍歷完所有劃分?jǐn)?shù)據(jù)集的屬性,或者每個(gè)分支下的所有的實(shí)例都具有相同的分類。如果所有實(shí)例具有相同的分類,則得到一個(gè)葉子節(jié)點(diǎn)或者終止塊。
[圖片上傳中。。。(1)]
在代碼最前面,輸入
import operator
并輸入以下代碼
# 得出次數(shù)最多的分類名稱
def majorityCnt(classList):
classCount = {}
for vote in classList:
if vote not in classCount.keys():
calssCount[vote] = 0
classCount[vote] +=1
sortedClassConnt = sorted(calssCount.iteritems(),key=operator.itemgetter(1),reverse=True)
return sortedClassConnt[0][0]
函數(shù)使用分類名稱的列表,然后創(chuàng)創(chuàng)建鍵值為classList中唯一值得數(shù)據(jù)字典,字典對(duì)象存儲(chǔ)了classList中每個(gè)類標(biāo)簽出現(xiàn)的頻率,利用operator操作鍵值排序字典,返回出現(xiàn)次數(shù)最多的分類名稱。
下面給出創(chuàng)建樹的代碼:
def createTree(dataSet,labels):
classList = [example[-1] for example in dataSet]
#類別完全相同則停止繼續(xù)劃分
if classList.count(classList[0]) ==len(classList):
return classList[0]
#遍歷完所有的特征時(shí)返回出現(xiàn)次數(shù)最多的類別
if len(dataSet[0]) == 1:
return majorityCnt(classList)
bestFeat = chooseBestFeatureToSplit(dataSet)
bestFeatLabel = labels[bestFeat]
myTree = {bestFeatLabel:{}}
del(labels[bestFeat])
#得到列表包含的所有屬性
featValues = [example[bestFeat] for example in dataSet]
uniqueVals = set(featValues)
for value in uniqueVals:
subLabels = labels[:]
myTree[bestFeatLabel][value] = createTree(splitDataSet\
(dataSet,bestFeat,value),subLabels)
return myTree
執(zhí)行以下命令,測(cè)試代碼:
In [185]: reload(trees)
Out[185]: <module 'trees' from 'trees.py'>
In [186]: myDat,labels=trees.createDataSet()
In [187]: myTree=trees.createTree(myDat,labels)
In [188]: myTree
Out[188]: {'no surfacing': {0: 'no', 1: {'flippers': {0: 'no', 1: 'yes'}}}}
3.2 在python中使用matplotlib注解繪制樹形圖
給出的字典形式并不容易理解。決策樹的優(yōu)點(diǎn)就是直觀易于理解。
于是我們自己繪制樹形圖。
3.2.1 Matplotlib 注解
由于字典的表示形式不好理解,所以我們使用matplotlib這個(gè)庫(kù)來(lái)創(chuàng)建樹形圖。
Matplotlib 提供了一個(gè)工具annotations,它可以在數(shù)據(jù)圖形上添加文本注解。注解同城用于解釋數(shù)據(jù)的內(nèi)容。
在計(jì)算機(jī)科學(xué)中,圖是一種數(shù)據(jù)結(jié)構(gòu),用于表示數(shù)學(xué)上的概念。
接下來(lái)我們創(chuàng)建新的treePlotter.py文件
3-5 使用文本注解繪制樹節(jié)點(diǎn)
#定義文本框和箭頭格式
decisionNode = dict(boxstyle = "sawtooth", fc = "0.8")
leafNode = dict(boxstyle = "round4", fc = "0.8")
arrow_args = dict(arrowstyle = "<-")
#繪制帶箭頭的注解,createPlot.ax1是一個(gè)全局變量
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)
#創(chuàng)建新圖形并清空繪圖區(qū),在繪圖區(qū)繪制決策節(jié)點(diǎn)和葉節(jié)點(diǎn)
def createPlot():
fig = plt.figure(1,facecolor = 'white')
fig.clf()
createPlot.ax1 = plt.subplot(111,frameon = False)
plotNode('decisionNodes',(0.5,0.1),(0.1,0.5),decisionNode)
plotNode('leafNodes',(0.8,0.1),(0.3,0.8),leafNode)
plt.show()
測(cè)試一下代碼:
In [6]: import treePlotter
In [7]: reload(treePlotter)
Out[7]: <module 'treePlotter' from 'treePlotter.py'>
In [8]: treePlotter.createPlot()
3.2.2 構(gòu)造注解樹
構(gòu)造完整的一棵樹,我們還需要知道,如何放置樹節(jié)點(diǎn),需要知道有多少個(gè)葉節(jié)點(diǎn),便于確定x軸的長(zhǎng)度,需要知道樹多少層,便于正確確定y軸的高度。
獲取葉節(jié)點(diǎn)的數(shù)目和樹的層數(shù)
def getNumLeafs(myTree):
numLeafs = 0
firstStr = myTree.keys()[0]
secondDict = myTree[firstStr]
for key in secondDict.keys():
#type()函數(shù),測(cè)試節(jié)點(diǎn)的數(shù)據(jù)類型是否為字典
if type(secondDict[key]).__name__ =='dict':
numLeafs += getNumLeafs(secondDict[key])
else:
numLeafs += 1
return numLeafs
#計(jì)算遍歷過(guò)程中的遇到判斷節(jié)點(diǎn)的個(gè)數(shù)
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
#如果達(dá)到子節(jié)點(diǎn),則從遞歸調(diào)用中返回
if thisDepth > maxDepth:
maxDepth = 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]
測(cè)試代碼:
In [39]: import treePlotter
In [40]: reload(treePlotter)
Out[40]: <module 'treePlotter' from 'treePlotter.py'>
In [41]: myTree = treePlotter.retrieveTree(1)
In [42]: treePlotter.getTreeDepth(myTree)
Out[42]: 2
In [43]: treePlotter.getNumLeafs(myTree)
Out[43]: 3
將下面的代碼添加到treePlotter.py中。
# plotTree函數(shù)
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)
'''
全局變量plotTree.tatolW存儲(chǔ)樹的寬度
全局變量plotTree.tatolD存儲(chǔ)樹的高度
plotTree.xOff和plotTree.yOff追蹤已經(jīng)繪制的節(jié)點(diǎn)位置
'''
def plotTree(myTree,parentPt,nodeTxt):
#計(jì)算寬與高
numLeafs = getNumLeafs(myTree)
depth = getTreeDepth(myTree)
firstStr = myTree.keys()[0]
cntrPt = (plotTree.xOff+(1.0+float(numLeafs))/2.0/plotTree.totalW,plotTree.yOff)
#標(biāo)記子節(jié)點(diǎn)屬性值
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:
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
繼續(xù)測(cè)試代碼:
In [5]: import treePlotter
In [6]: reload(treePlotter)
Out[6]: <module 'treePlotter' from 'treePlotter.pyc'>
In [7]: myTree = treePlotter.retrieveTree(0)
In [44]: treePlotter.createPlot(myTree)

In [8]: myTree['no surfacing'][3] = 'maybe'
In [9]: myTree
Out[9]: {'no surfacing': {0: 'no', 1: {'flippers': {0: 'no', 1: 'yes'}}, 3: 'maybe'}}
In [10]: treePlotter.createPlot(myTree)
3.3 測(cè)試算法: 使用決策樹執(zhí)行分類
在trees.py中,添加下面的代碼
#使用決策樹的分類函數(shù)
def classify(inputTree,featLabels,testVec):
firstStr = inputTree.keys()[0]
secondDict = inputTree[firstStr]
#將標(biāo)簽字符串轉(zhuǎn)換為索引
featIndex = featLabels.index(firstStr)
for key in secondDict.keys():
if testVec[featIndex] == key:
if type(secondDict[key]).__name__ == 'dict':
classLabel = classify(secondDict[key],featLabels,testVec)
else:
classLabel = secondDict[key]
return classLabel
測(cè)試代碼
In [11]: import trees
In [12]: reload(trees)
Out[12]: <module 'trees' from 'trees.pyc'>
In [14]: myDat,labels = trees.createDataSet()
In [15]: labels
Out[15]: ['no surfacing', 'flippers']
In [16]: myTree = treePlotter.retrieveTree(0)
In [17]: myTree
Out[17]: {'no surfacing': {0: 'no', 1: {'flippers': {0: 'no', 1: 'yes'}}}}
In [18]: trees.classify(myTree,labels,[1,1])
Out[18]: 'yes'
In [19]: trees.classify(myTree,labels,[1,0])
Out[19]: 'no'
將此結(jié)果與之前的圖做比較,不難發(fā)現(xiàn),結(jié)果相符。
3.3.2 使用算法 :決策樹的存儲(chǔ)
構(gòu)造決策樹是一個(gè)很耗時(shí)的事情,如果數(shù)據(jù)集很大,將會(huì)非常耗時(shí)間。為此,我們調(diào)用python模塊的pickle序列化對(duì)象。序列化對(duì)象可以在磁盤上保存文件,并在需要的時(shí)候讀取出來(lái)。
#使用pickle模塊存儲(chǔ)決策樹
def storeTree(inputTree,filename) :
import pickle
fw = open(filename, 'w')
pickle.dump(inputTree,fw)
fw.close
def grabTree(filename):
import pickle
fr = open(filename)
return pickle.load(fr)
測(cè)試代碼:
In [22]: reload(trees)
Out[22]: <module 'trees' from 'trees.py'>
In [23]: trees.storeTree(myTree,r'E:\ML\ML_source_code\mlia\Ch03\classifierStorage.txt')
In [24]: trees.grabTree(r'E:\ML\ML_source_code\mlia\Ch03\classifierStorage.txt')
Out[24]: {'no surfacing': {0: 'no', 1: {'flippers': {0: 'no', 1: 'yes'}}}}
通過(guò)上面的代碼,我們可以對(duì)數(shù)據(jù)分類時(shí)重新學(xué)習(xí)一遍。
3.4 示例:使用決策樹預(yù)測(cè)隱形眼鏡類型
眼科醫(yī)生是如何判斷患者需要佩戴的鏡片類型的。
由于前面已經(jīng)寫好了算法模塊:
我們載入本地的數(shù)據(jù)集之后,可以直接測(cè)試代碼:
In [5]: import trees
In [6]: reload(trees)
Out[6]: <module 'trees' from 'trees.pyc'>
In [8]: import treePlotters
In [9]: reload(treePlotters)
Out[9]: <module 'treePlotters' from 'treePlotters.pyc'>
In [11]: fr = open(r'E:\ML\ML_source_code\mlia\Ch03\lenses.txt')
In [12]: lenses = [inst.strip().split('\t') for inst in fr.readlines()]
In [13]: lensesLabels = ['age','prescript','astigmatic','tearRate']
In [14]: lensesTree = trees.createTree(lenses,lensesLabels)
In [15]: lensesTree
Out[15]:
{'tearRate': {'normal': {'astigmatic': {'no': {'age': {'pre': 'soft',
'presbyopic': {'prescript': {'hyper': 'soft', 'myope': 'no lenses'}},
'young': 'soft'}},
'yes': {'prescript': {'hyper': {'age': {'pre': 'no lenses',
'presbyopic': 'no lenses',
'young': 'hard'}},
'myope': 'hard'}}}},
'reduced': 'no lenses'}}
In [17]: treePlotters.createPlot(lensesTree)
最終得到上面這個(gè)圖,可是這些匹配選項(xiàng)可能太多了,我們將這些問(wèn)題稱之為過(guò)度匹配。
為了減少這個(gè)問(wèn)題,我們可以裁剪決策樹,去掉一些不必要的子節(jié)點(diǎn)。