機器學習實戰-決策樹

第二章介紹的k-近鄰算法可以完成很多分類任務,但是它最大的缺點就是無法給出數據內在的含義,決策樹的主要優勢在于數據形式非常容易理解。

決策樹
優點:計算復雜度不高,輸出結果易于理解,對中間值的缺失不敏感,可以處理不相關特征數據。
缺點:可能會產生過度匹配的問題
適用數據類型:數值型和標稱型

先計算給定數據集的香農熵

在CSDN的Markdown中,第一行居然不居中,簡書的是默認居中了

序號 不浮出水面是否可以生存 是否有腳蹼 屬于魚類
1 1 1 1
2 1 1 1
3 1 0 0
3 0 1 0
3 0 1 0
from math import log

def calcShannonEnt(dataSet):
    numEntries = len(dataSet)
    labelCounts = {}
    #為所有可能的分類創建字典
    for featVec in dataSet:
        currentLabel = featVec[-1]
        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求對數
        shannonEnt -= prob*log(prob,2)
    return shannonEnt

def createDataSet():
    dataSet = [[1,1,'yes'],
               [1,1,'yes'],
               [1,0,'no'],
               [0,1,'no'],
               [0,1,'no']]
    labels = ['no surfacing','flippers']
    return dataSet,labels

測試數據集的熵

import trees
reload(trees)
myDat,labels = trees.createDataSet()
>>> myDat
[[1, 1, 'yes'], [1, 1, 'yes'], [1, 0, 'no'], [0, 1, 'no'], [0, 1, 'no']]
>>> trees.calcShannonEnt(myDat)
0.9709505944546686

熵越高,則混合的數據也越多
增加一個測試分類來測試熵的變化:

>>> myDat[0][-1]='maybe'
>>> myDat
[[1, 1, 'maybe'], [1, 1, 'yes'], [1, 0, 'no'], [0, 1, 'no'], [0, 1, 'no']]
>>> trees.calcShannonEnt(myDat)
1.3709505944546687

下面,開始劃分數據集:

def splitDataSet(dataSet, axis, value):
    retDataSet = []
    for featVec in dataSet:
        #將符合要求的數據集添加到列表中
        if featVec[axis] == value:
            reducedFeatVec = featVec[:axis]
            reducedFeatVec.extend(featVec[axis+1:])
            retDataSet.append(reducedFeatVec)
    return retDataSet

本段代碼使用了三個輸入參數:待劃分的數據集,劃分數據集的特征,需要返回的特征的值。
然后在Python命令提示符內輸入下述命令:

>>> myDat
[[1, 1, 'yes'], [1, 1, 'yes'], [1, 0, 'no'], [0, 1, 'no'], [0, 1, 'no']]
>>> trees.splitDataSet(myDat,0,1)
[[1, 'yes'], [1, 'yes'], [0, 'no']]
>>> trees.splitDataSet(myDat,0,0)
[[1, 'no'], [1, 'no']]
>>> 

接下來我們開始遍歷整個數據集,循環計算香農熵和splitDataSet()函數,找到最好的特征劃分方式。

def chooseBestFeatureToSplit(dataSet):
    numFeatures = len(dataSet[0]) - 1
    baseEntropy = calcShannonEnt(dataSet)#計算原始香農熵
    bastInfoGain = 0.0;baseFeature = -1
    for i in range(numFeatures):
        featList = [example[i] for example in dataSet]
        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

從列表中新建集合是Python語言得到列表中唯一元素的最快方法

下面開始測試上面代碼的實際輸出結果

>>> trees.chooseBestFeatureToSplit(myDat)
0
>>> myDat
[[1, 1, 'yes'], [1, 1, 'yes'], [1, 0, 'no'], [0, 1, 'no'], [0, 1, 'no']]

代碼告訴我們,第0個特征是最好的用于劃分數據集的特征

下面我們開始采用遞歸的方式處理數據集

如果數據集已經處理了所有屬性,但是類標簽依然不是唯一的,此時我們需要決定如何定義該葉子節點,在這種情況下,我們通常會采用多數表決的方法決定該葉子節點的分類

import operator
def majorityCnt(classList):
    classCount = {}
    for vote in classList:#統計數據字典classList每一個類標簽出現的頻率
        if vote not in classCount.keys(): classCount[vote] = 0
        classCount[vote] += 1
    sortedClassCount = sorted(classCount.iteritems(), key=operator.itemgette(1), reverse=True)#排序
    return sortedClassCount[0][0]#返回次數最多的

下面開始加入創建樹的函數代碼

def createTree(dataSet, labels):#數據集,標簽列表
    classList = [example[-1] for example in dataSet]#最后一個屬性加入列表變量classList
    #類別完全相同則停止劃分
    if classList.count(classList[0]) == len(classList):
        return classList[0]
    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

subLabels = labels[:],這行代碼復制了類標簽,并將其存儲在新列表變量subLabels中。之所以這樣做,是因為在Python語言中,函數參數是列表類型時,參數是按照引用方式傳遞的。為了保證每次調用函數createTree()時不改變原始列表的內容,使用新變量subLabels代替原始列表。

下面是測試實際輸出結果

#trees-1.py
import trees
reload(trees)
myDat,labels = trees.createDataSet()
myTree = trees.createTree(myDat,labels)
>>> myTree
{'no surfacing': {0: 'no', 1: {'flippers': {0: 'no', 1: 'yes'}}}}

下面開始學習使用Matplotlib畫圖

#-*- coding=utf-8 -*-

import matplotlib.pyplot as plt


decisionNode = dict(boxstyle="sawtooth",fc="0.8")
leafNode = dict(boxstyle="round4",fc="0.8")
arrow_args = dict(arrowstyle="<-")

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 )



def createPlot():
    fig = plt.figure(1,facecolor='white')
    fig.clf()
    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()
函數plotNode例圖

下面開始獲取葉節點的數目和樹的層數

def getNumLeafs(myTree):
    numLeafs = 0
    firstStr = myTree.keys()[0]
    secondDict = myTree[firstStr]
    for key in secondDict.keys():
        if type(secondDict[key]).__name__=='dict':
             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

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]
>>> import treePlotter
>>> treePlotter.retrieveTree(1)
{'no surfacing': {0: 'no', 1: {'flippers': {0: {'head': {0: 'no', 1: 'yes'}}, 1: 'no'}}}}
>>> myTree = treePlotter.retrieveTree(0)
>>> treePlotter.getNumLeafs(myTree)
3
>>> treePlotter.getTreeDepth(myTree)
2

更新部分代碼,開始嘗試畫圖

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)
    
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)
    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

并更新creaePlot()部分的代碼

def createPlot(inTree):
    fig = plt.figure(1,facecolor='white')
    fig.clf()
    axprops = dict(xticks=[], yticks=[])
    createPlot.ax1 = plt.subplot(111,frameon=False, **axprops)
    plotTree.totalW = float(getNumLeafs(inTree))#寬度
    plotTree.totalD = float(getTreeDepth(inTree))#高度
    plotTree.xOff = -0.5/plotTree.totalW;plotTree.yOff = 1.0;
    plotTree(inTree, (0.5,1.0),'')
    plt.show()

開始畫圖

#treePlotter-1.py
import treePlotter
myTree=treePlotter.retrieveTree(0)
treePlotter.createPlot(myTree)
圖3-6

接著添加字典的內容,重新繪制圖片

>>> myTree['no surfacing'][3] = 'maybe'
>>> myTree
{'no surfacing': {0: 'no', 1: {'flippers': {0: 'no', 1: 'yes'}}, 3: 'maybe'}}
>>> treePlotter.createPlot(myTree)
圖3-7

下面開始重點講如何利用決策樹執行數據分類
在執行數據分類時,需要使用決策樹以及用于構造決策樹的標簽向量。然后,程序比較測試數據與決策樹上的數值,遞歸執行該過程直到進入葉子節點;最后將測試數據定義為葉子節點所屬的類型。

#使用決策樹的分類函數
#添加到trees.py
def classify(inputTree, featLabels, testVec):
    firstStr = inputTree.keys()[0]
    secondDict = inputTree[firstStr]
    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]
    #key = testVec[featIndex]
    #valueOfFeat = secondDict[key]
    #if isinstance(valueOfFeat, dict):#是否是實例
    #    classLabel = classify(valueOfFeat, featLabels, testVec)
    #else: classLabel = valueOfFeat
    return classLabel
#trees-1
import trees
import treePlotter
myDat,labels = trees.createDataSet()
myTree=treePlotter.retrieveTree(0)
>>> labels
['no surfacing', 'flippers']
>>> myTree
{'no surfacing': {0: 'no', 1: {'flippers': {0: 'no', 1: 'yes'}}}}
>>> trees.classify(myTree,labels,[1,0])
'no'
>>> trees.classify(myTree,labels,[1,1])
'yes'

下面開始在硬盤上存儲決策樹分類器

#trees.py
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)
#tree-1.py
import trees
import treePlotter
myDat,labels = trees.createDataSet()
myTree = trees.createTree(myDat,labels)
trees.storeTree(myTree,'classifierStorage.txt')
>>> trees.grabTree('classifierStorage.txt')
{'no surfacing': {0: 'no', 1: {'flippers': {0: 'no', 1: 'yes'}}}}
import trees
import treePlotter
myDat,labels = trees.createDataSet()
myTree = trees.createTree(myDat,labels)

fr=open('lenses.txt')
lenses=[inst.strip().split('\t') for inst in fr.readlines()]
lensesLabels=['age','prescript','astigmatic','tearRate']
lensesTree = trees.createTree(lenses,lensesLabels)
>>> treePlotter.createPlot(lensesTree)
ID3算法產生的決策樹
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市,隨后出現的幾起案子,更是在濱河造成了極大的恐慌,老刑警劉巖,帶你破解...
    沈念sama閱讀 229,836評論 6 540
  • 序言:濱河連續發生了三起死亡事件,死亡現場離奇詭異,居然都是意外死亡,警方通過查閱死者的電腦和手機,發現死者居然都...
    沈念sama閱讀 99,275評論 3 428
  • 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人,你說我怎么就攤上這事。” “怎么了?”我有些...
    開封第一講書人閱讀 177,904評論 0 383
  • 文/不壞的土叔 我叫張陵,是天一觀的道長。 經常有香客問我,道長,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 63,633評論 1 317
  • 正文 為了忘掉前任,我火速辦了婚禮,結果婚禮上,老公的妹妹穿的比我還像新娘。我一直安慰自己,他們只是感情好,可當我...
    茶點故事閱讀 72,368評論 6 410
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著,像睡著了一般。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發上,一...
    開封第一講書人閱讀 55,736評論 1 328
  • 那天,我揣著相機與錄音,去河邊找鬼。 笑死,一個胖子當著我的面吹牛,可吹牛的內容都是我干的。 我是一名探鬼主播,決...
    沈念sama閱讀 43,740評論 3 446
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了?” 一聲冷哼從身側響起,我...
    開封第一講書人閱讀 42,919評論 0 289
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后,有當地人在樹林里發現了一具尸體,經...
    沈念sama閱讀 49,481評論 1 335
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內容為張勛視角 年9月15日...
    茶點故事閱讀 41,235評論 3 358
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發現自己被綠了。 大學時的朋友給我發了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 43,427評論 1 374
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖,靈堂內的尸體忽然破棺而出,到底是詐尸還是另有隱情,我是刑警寧澤,帶...
    沈念sama閱讀 38,968評論 5 363
  • 正文 年R本政府宣布,位于F島的核電站,受9級特大地震影響,放射性物質發生泄漏。R本人自食惡果不足惜,卻給世界環境...
    茶點故事閱讀 44,656評論 3 348
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧,春花似錦、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 35,055評論 0 28
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至,卻和暖如春,著一層夾襖步出監牢的瞬間,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 36,348評論 1 294
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人。 一個月前我還...
    沈念sama閱讀 52,160評論 3 398
  • 正文 我出身青樓,卻偏偏與公主長得像,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當晚...
    茶點故事閱讀 48,380評論 2 379

推薦閱讀更多精彩內容

  • 簡述 本章構造的決策樹算法能夠讀取數據集合,構建類似于圖3-1的決策樹。決策樹很多任務都 是為了數據中所蘊含的知識...
    芮芮cat閱讀 385評論 0 1
  • 決策樹 決策樹是一個選擇的過程,以樹的結構來展示,其每個非葉節點表示一個特征屬性上的測試,每個分支代表這個特征屬性...
    z3r0me閱讀 292評論 0 0
  • 【主要內容】 決策樹簡介 數據集中度量一致性 使用遞歸構造決策樹 使用Matplotlib繪制樹 【數據集度量】 ...
    小二金剛閱讀 363評論 0 0
  • 正方形代表判斷模塊(decision block) ,橢圓代表終止模塊(terminating block),表示...
    凌岸_ing閱讀 2,392評論 0 1
  • 欣媛姓彭,彈一曲高山流水,寫一手清麗小文。 八月的晚風透著絲絲的悶熱,連平時經常遛狗的爺爺出去了一會就回來了。這個...
    亮子說閱讀 567評論 0 0