1. 程式人生 > >機器學習實戰python版第三章決策樹程式碼理解

機器學習實戰python版第三章決策樹程式碼理解

今天開始學習第三章決策樹。

前面對決策樹的講解我就不寫了,書上寫的都很清楚,就是根據特徵的不同逐步的對資料進行分類,形狀像一個倒立的樹。決策樹演算法比kNN的演算法複雜度要低,理解起來也有一定難度。

資訊增益

每一組資料都有自己的熵,資料要整齊,熵越低。也就是說屬於同一類的資料熵低,越混合的資料熵越高。計算資料集的熵程式碼如下:

<span style="font-size:24px;">def calcShannonEnt(dataSet):
    numEntries = len(dataSet)#資料集的行
    labelCounts = {}
    for featVec in dataSet: #the the number of unique elements and their occurance
        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
        shannonEnt -= prob * log(prob,2) #log base 2
    return shannonEnt
</span>

劃分資料集

就是根據一個特徵把資料進行劃分。程式碼如下:

<span style="font-size:24px;">def splitDataSet(dataSet,axis,value):
    retDataSet = []
    for featVec in dataSet:
        if featVec[axis] == value:
            reducedFeatVec = featVec[:axis]#axis = 0時 這個列表是空的
            reducedFeatVec.extend(featVec[axis + 1:])
            retDataSet.append(reducedFeatVec)
    return retDataSet</span>

append,和extend這兩個函式很有意思。

結果如下:

<span style="font-size:24px;">>>> import trees
>>> myDat,labels = trees.createDataSet()
>>> 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']]</span>

但是實際操作中我們不能總能人工輸入分類依據的特徵。我們需要機器根據資料的特徵自己判斷最佳的分類特徵。程式碼如下:

<span style="font-size:24px;">def chooseBestFeatureToSplit(dataSet):
    numFeatures = len(dataSet[0]) - 1      #列減一
    baseEntropy = calcShannonEnt(dataSet)
    bestInfoGain = 0.0; bestFeature = -1
    for i in range(numFeatures):        # 012遍歷資料集
        featList = [example[i] for example in dataSet]#create a list of all the examples of this feature全部資料組的第i個數據,
        uniqueVals = set(featList)       #資料組的集,即{0,1}。{yes,no}
        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     #calculate the info gain; ie reduction in entropy熵越低越好。
        if (infoGain > bestInfoGain):       #compare this to the best gain so far
            bestInfoGain = infoGain         #if better than current best, set to best
            bestFeature = i
    return bestFeature                      #returns an integer</span>


結果如下:

<span style="font-size:24px;">>>> import trees
>>> myDat,labels = trees.createDataSet()
>>> trees.chooseBestFeatureToSplit(myDat)
0</span>

建立決策樹

書中的內容還是比較好理解的,樹的建立理論也寫得很詳細,主要是程式碼比較難懂,因為python的程式碼很簡潔,所以看起來也就更難一些。

建立樹的函式程式碼:

<span style="font-size:24px;">def majorityCnt(classList):
    classCount={}
    for vote in classList:
        if vote not in classCount.keys(): classCount[vote] = 0
        classCount[vote] += 1
    sortedClassCount = sorted(classCount.iteritems(), key=operator.itemgetter(1), reverse=True)
    return sortedClassCount[0][0]

def createTree(dataSet,labels):
    classList = [example[-1] for example in dataSet]
    if classList.count(classList[0]) == len(classList): 
        return classList[0]#stop splitting when all of the classes are equal
    if len(dataSet[0]) == 1: #stop splitting when there are no more features in dataSet
        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[:]       #copy all of labels, so trees don't mess up existing labels
        myTree[bestFeatLabel][value] = createTree(splitDataSet(dataSet, bestFeat, value),subLabels)
    return myTree                            
    </span>

首先這是一個遞迴函式,就是函式自己不停的呼叫自己,當遇到結束情況時在一步步返回。
if classList.count(classList[0]) == len(classList):
        return classList[0]#stop splitting when all of the classes are equal

類的資料都是一樣的時候

 if len(dataSet[0]) == 1: #stop splitting when there are no more features in dataSet
        return majorityCnt(classList)
只有一個數據的時候
myTree = {bestFeatLabel:{}}建立一個樹,為了後面的賦值。

del(labels[bestFeat])刪除類標籤
featValues = [example[bestFeat] for example in dataSet]
uniqueVals = set(featValues)
for value in uniqueVals:
subLabels = labels[:]       #copy all of labels, so trees don't mess up existing labels
myTree[bestFeatLabel][value] = createTree(splitDataSet(dataSet, bestFeat, value),subLabels)遞迴,每次呼叫兩個creatTree,分兩個字典給賦值。

結果如下:

<span style="font-size:24px;">>>> myDat,labels = trees.createDataSet()
>>> myTree = trees.createTree(myDat,labels)
>>> myTrees

Traceback (most recent call last):
  File "<pyshell#10>", line 1, in <module>
    myTrees
NameError: name 'myTrees' is not defined
>>> myTree
{'no surfacing': {0: 'no', 1: {'flippers': {0: 'no', 1: 'yes'}}}}</span>

下面的內容明天再寫,希望大家多多指導!