機(jī)器學(xué)習(xí)實戰(zhàn)之決策樹(三)


正方形代表判斷模塊(decision block) ,橢圓代表終止模塊(terminating block)桨啃,表示已經(jīng)得到結(jié)論凰盔,可以終止運動。

決策樹的優(yōu)勢在于數(shù)據(jù)形式容易理解紊扬。
決策樹的很多任務(wù)都是為了數(shù)據(jù)中所蘊含的知識信息。
決策樹可以使用不熟悉的數(shù)據(jù)集合唉擂,并從中提取出一系列規(guī)則餐屎,機(jī)器學(xué)習(xí)算法最終將使用這些機(jī)器從數(shù)據(jù)集中創(chuàng)造的規(guī)則。

3.1決策樹的構(gòu)造

優(yōu)點:計算復(fù)雜度不高玩祟,輸出結(jié)果易于理解腹缩,對中間值的缺失不敏感,可以處理不相關(guān)特征數(shù)據(jù)空扎。
缺點:可能會產(chǎ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()
檢測數(shù)據(jù)集中的每個子項是否屬于同一分類:

    If so return 類標(biāo)簽 :
    Else
           尋找劃分?jǐn)?shù)據(jù)集的最好特征
           劃分?jǐn)?shù)據(jù)集
           創(chuàng)建分支節(jié)點
                   for 每個劃分的子集
                           調(diào)用函數(shù)createBranch 并增加返回結(jié)果到分支節(jié)點中
            return   分子節(jié)點

上面的偽代碼createBranch是一個遞歸函數(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)。
測試算法:使用經(jīng)驗樹計算錯誤概率
使用算法:此步驟可以適應(yīng)于任何監(jiān)督學(xué)習(xí)算法常潮,而使用決策樹可以更好的理解數(shù)據(jù)的內(nèi)在含義。

本次我們使用ID3算法來劃分?jǐn)?shù)據(jù)集楷力。每次劃分?jǐn)?shù)據(jù)集的時我們只選取一個特征值喊式。
決策樹學(xué)習(xí)采用的是自頂向下的遞歸方法,其基本思想是以信息熵為度量構(gòu)造一棵熵值下降最快的樹萧朝,到葉子節(jié)點處的熵值為零岔留,此時每個葉節(jié)點中的實例都屬于同一類。

3.1.1 信息增益
劃分?jǐn)?shù)據(jù)集的大原則是 :將無序的數(shù)據(jù)變得有序检柬。
組織雜亂無章數(shù)據(jù)的一種方法就是使用信息論度量信息献联,信息論是量化處理信息的分支科學(xué)。
在劃分?jǐn)?shù)據(jù)集之前之后的信息發(fā)生的變化稱之為信息增益何址,知道如何計算信息增益里逆,我們就可以計算每個特征的值劃分?jǐn)?shù)據(jù)集獲得的信息增益,獲得信息增益最高的特征就是最好的選擇用爪。
集合信息的度量方式稱之為 香農(nóng)熵原押。

熵是信息論中的概念,用來表示集合的無序程度偎血,熵越大表示集合越混亂诸衔,反之則表示集合越有序。熵的計算公式為:

E = -P * log2P

熵定義為信息的期望值颇玷。那什么是信息呢笨农?如果待分類的事務(wù)可能劃分在多個分類之中,負(fù)荷xi的信息定義為:


其中帖渠,p(xi)是選擇分類的概率谒亦。
為了計算熵,我們需要計算所有類別的



其中n是分類的數(shù)目阿弃。

接下來我們將使用pythoon計算信息熵诊霹,去度量數(shù)據(jù)集的無序程度,創(chuàng)建名為trees.py的文件渣淳。

from math import log

def calcShannonEnt(dataSet):
    #計算數(shù)據(jù)集中實例的總數(shù)
    numEntries = len(dataSet)
    #創(chuàng)建一個數(shù)據(jù)字典
    labelCounts = {}
    
    for featVec in dataSet:
        #取鍵值最后一列的數(shù)值的最后一個字符串
        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為底求對數(shù)
        shannonEnt -= prob * log(prob,2)
    return shannonEnt

我們輸入 一個數(shù)據(jù)來測試一下脾还。

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ù)集中添加更多的分類鄙漏,以此來觀測熵是如何變化的嗤谚。

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ù)集的無序程度(信息熵),還需要劃分?jǐn)?shù)據(jù)集怔蚌,度量劃分?jǐn)?shù)據(jù)集的熵巩步。以便于判斷當(dāng)前是否正確劃分了數(shù)據(jù)集。

我們隊每個特征劃分一次數(shù)據(jù)集的結(jié)果計算一次信息熵桦踊,然后去判斷按照哪個特征劃分?jǐn)?shù)據(jù)集是最好的劃分方式椅野。

代碼 : 按照給定的特征劃分?jǐn)?shù)據(jù)集

#dataSet:待劃分的數(shù)據(jù)集
#axis劃分?jǐn)?shù)據(jù)集的特征
#特征的返回值
def splitDataSet(dataSet,axis,value):
    #創(chuàng)建新的list對象
    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]

測試一下劃分?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']]

記下來我們會遍歷整個數(shù)據(jù)集籍胯,循環(huán)計算香農(nóng)熵和splitDataSet()函數(shù)竟闪,找到最好的特征劃分方式。熵計算會得出如何劃分?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個數(shù)據(jù)的第i個數(shù)據(jù)炼蛤,并寫入列表
        featList = [example[i] for example in dataSet]
        #將列表的數(shù)據(jù)集合在一起,并去重
        uniqueVals = set(featList)
        newEntropy = 0.0
        #計算每種劃分方式的信息熵
        for value in uniqueVals:
            subDataSet = splitDataSet(dataSet,i,value)
            prob = len(subDataSet)/float(len(dataSet))
            newEntropy += prob * calcShannonEnt(subDataSet)
        infoGain = baseEntropy - newEntropy
        #計算好信息熵增益
        if (infoGain > bestInfoGain):
            bestInfoGain = infoGain
            bestFeature = i
    return bestFeature

上述代碼實現(xiàn)選取特征蝶涩,劃分?jǐn)?shù)據(jù)集理朋,計算出最好的劃分?jǐn)?shù)據(jù)集的特征。
在函數(shù)的調(diào)用的數(shù)據(jù)中滿足一定的要求:
(1) 數(shù)據(jù)必須是一種由列表元素組成的列表绿聘,且所有的列表元素具有相同的數(shù)據(jù)長度嗽上。
(2) 數(shù)據(jù)最后一列或每個實例的最后一個元素是當(dāng)前實例的類別標(biāo)簽。

測試代碼:

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個特征就是最好的用于劃分?jǐn)?shù)據(jù)集的特征炸裆。

3.1.3 遞歸構(gòu)建決策樹
目前我們已經(jīng)給出了從數(shù)據(jù)集構(gòu)造決策樹算法所需要的子功能模塊,工作原理如下:
得到原始數(shù)據(jù)集鲜屏,然后基于最好的屬性值劃分?jǐn)?shù)據(jù)集烹看,由于特征值可能多于兩個,因此可能存在大于兩個分支的數(shù)據(jù)集劃分洛史。第一次劃分之后惯殊,數(shù)據(jù)將被鄉(xiāng)下傳遞到樹分支的下一個節(jié)點,在這個節(jié)點上也殖,可以再次劃分?jǐn)?shù)據(jù)土思。因此我們可以使用遞歸的原理來處理數(shù)據(jù)。

遞歸結(jié)束的條件是:程序遍歷完所有劃分?jǐn)?shù)據(jù)集的屬性忆嗜,或者每個分支下的所有的實例都具有相同的分類己儒。如果所有實例具有相同的分類,則得到一個葉子節(jié)點或者終止塊捆毫。

[圖片上傳中闪湾。。绩卤。(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ù)字典,字典對象存儲了classList中每個類標(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]
    #遍歷完所有的特征時返回出現(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í)行以下命令裆站,測試代碼:

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)點就是直觀易于理解。
于是我們自己繪制樹形圖宏胯。

3.2.1 Matplotlib 注解

由于字典的表示形式不好理解捂贿,所以我們使用matplotlib這個庫來創(chuàng)建樹形圖。
Matplotlib 提供了一個工具annotations胳嘲,它可以在數(shù)據(jù)圖形上添加文本注解。注解同城用于解釋數(shù)據(jù)的內(nèi)容扣草。


在計算機(jī)科學(xué)中了牛,圖是一種數(shù)據(jù)結(jié)構(gòu),用于表示數(shù)學(xué)上的概念辰妙。


接下來我們創(chuàng)建新的treePlotter.py文件

3-5 使用文本注解繪制樹節(jié)點

#定義文本框和箭頭格式
decisionNode = dict(boxstyle = "sawtooth", fc = "0.8")
leafNode =  dict(boxstyle = "round4", fc = "0.8")
arrow_args = dict(arrowstyle = "<-")

#繪制帶箭頭的注解,createPlot.ax1是一個全局變量
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é)點和葉節(jié)點
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()

測試一下代碼:

In [6]: import treePlotter

In [7]: reload(treePlotter)
Out[7]: <module 'treePlotter' from 'treePlotter.py'>

In [8]: treePlotter.createPlot()
plotNode_example.png

3.2.2 構(gòu)造注解樹

構(gòu)造完整的一棵樹,我們還需要知道密浑,如何放置樹節(jié)點蛙婴,需要知道有多少個葉節(jié)點,便于確定x軸的長度尔破,需要知道樹多少層街图,便于正確確定y軸的高度。

獲取葉節(jié)點的數(shù)目和樹的層數(shù)

def getNumLeafs(myTree):
    numLeafs = 0
    firstStr = myTree.keys()[0]
    secondDict = myTree[firstStr]
    for key in secondDict.keys():
        #type()函數(shù),測試節(jié)點的數(shù)據(jù)類型是否為字典
        if type(secondDict[key]).__name__ =='dict':
            numLeafs += getNumLeafs(secondDict[key])
        else:
            numLeafs += 1
    return numLeafs 

#計算遍歷過程中的遇到判斷節(jié)點的個數(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à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]


測試代碼:
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存儲樹的寬度
全局變量plotTree.tatolD存儲樹的高度
plotTree.xOff和plotTree.yOff追蹤已經(jīng)繪制的節(jié)點位置
'''   
def plotTree(myTree,parentPt,nodeTxt):
    #計算寬與高
    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é)點屬性值
    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ù)測試代碼:

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)

![決策樹.png](http://upload-images.jianshu.io/upload_images/3668059-738fcb261a2b616c.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)

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)
決策樹2.png

3.3 測試算法: 使用決策樹執(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  

測試代碼

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 使用算法 :決策樹的存儲
構(gòu)造決策樹是一個很耗時的事情秩霍,如果數(shù)據(jù)集很大篙悯,將會非常耗時間。為此铃绒,我們調(diào)用python模塊的pickle序列化對象鸽照。序列化對象可以在磁盤上保存文件,并在需要的時候讀取出來匿垄。

#使用pickle模塊存儲決策樹
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)

測試代碼:

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'}}}}

通過上面的代碼移宅,我們可以對數(shù)據(jù)分類時重新學(xué)習(xí)一遍归粉。

3.4 示例:使用決策樹預(yù)測隱形眼鏡類型
眼科醫(yī)生是如何判斷患者需要佩戴的鏡片類型的。
由于前面已經(jīng)寫好了算法模塊:

我們載入本地的數(shù)據(jù)集之后漏峰,可以直接測試代碼:

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)
lenses.png

最終得到上面這個圖糠悼,可是這些匹配選項可能太多了,我們將這些問題稱之為過度匹配浅乔。
為了減少這個問題倔喂,我們可以裁剪決策樹,去掉一些不必要的子節(jié)點靖苇。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末席噩,一起剝皮案震驚了整個濱河市,隨后出現(xiàn)的幾起案子贤壁,更是在濱河造成了極大的恐慌悼枢,老刑警劉巖,帶你破解...
    沈念sama閱讀 217,277評論 6 503
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件脾拆,死亡現(xiàn)場離奇詭異馒索,居然都是意外死亡,警方通過查閱死者的電腦和手機(jī)名船,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,689評論 3 393
  • 文/潘曉璐 我一進(jìn)店門绰上,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人渠驼,你說我怎么就攤上這事蜈块。” “怎么了迷扇?”我有些...
    開封第一講書人閱讀 163,624評論 0 353
  • 文/不壞的土叔 我叫張陵百揭,是天一觀的道長。 經(jīng)常有香客問我谋梭,道長信峻,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 58,356評論 1 293
  • 正文 為了忘掉前任瓮床,我火速辦了婚禮盹舞,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘隘庄。我一直安慰自己踢步,他們只是感情好,可當(dāng)我...
    茶點故事閱讀 67,402評論 6 392
  • 文/花漫 我一把揭開白布丑掺。 她就那樣靜靜地躺著获印,像睡著了一般。 火紅的嫁衣襯著肌膚如雪街州。 梳的紋絲不亂的頭發(fā)上兼丰,一...
    開封第一講書人閱讀 51,292評論 1 301
  • 那天玻孟,我揣著相機(jī)與錄音,去河邊找鬼鳍征。 笑死黍翎,一個胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的艳丛。 我是一名探鬼主播匣掸,決...
    沈念sama閱讀 40,135評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼氮双!你這毒婦竟也來了碰酝?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 38,992評論 0 275
  • 序言:老撾萬榮一對情侶失蹤戴差,失蹤者是張志新(化名)和其女友劉穎送爸,沒想到半個月后,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體暖释,經(jīng)...
    沈念sama閱讀 45,429評論 1 314
  • 正文 獨居荒郊野嶺守林人離奇死亡碱璃,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 37,636評論 3 334
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發(fā)現(xiàn)自己被綠了饭入。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 39,785評論 1 348
  • 序言:一個原本活蹦亂跳的男人離奇死亡肛真,死狀恐怖谐丢,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情蚓让,我是刑警寧澤乾忱,帶...
    沈念sama閱讀 35,492評論 5 345
  • 正文 年R本政府宣布,位于F島的核電站历极,受9級特大地震影響窄瘟,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜趟卸,卻給世界環(huán)境...
    茶點故事閱讀 41,092評論 3 328
  • 文/蒙蒙 一蹄葱、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧锄列,春花似錦图云、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,723評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至筒严,卻和暖如春丹泉,著一層夾襖步出監(jiān)牢的瞬間情萤,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 32,858評論 1 269
  • 我被黑心中介騙來泰國打工摹恨, 沒想到剛下飛機(jī)就差點兒被人妖公主榨干…… 1. 我叫王不留筋岛,地道東北人。 一個月前我還...
    沈念sama閱讀 47,891評論 2 370
  • 正文 我出身青樓睬塌,卻偏偏與公主長得像泉蝌,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子揩晴,可洞房花燭夜當(dāng)晚...
    茶點故事閱讀 44,713評論 2 354

推薦閱讀更多精彩內(nèi)容