熱線電話:13121318867

登錄
首頁精彩閱讀數據挖掘之決策樹歸納算法的Python實現
數據挖掘之決策樹歸納算法的Python實現
2018-06-17
收藏

數據挖掘決策樹歸納算法的Python實現

引自百度:決策樹算法是一種逼近離散函數值的方法。它是一種典型的分類方法,首先對數據進行處理,利用歸納算法生成可讀的規則和決策樹,然后使用決策對新數據進行分析。本質上決策樹是通過一系列規則對數據進行分類的過程
決策樹的算法原理:
(1)通過把實例從根節點開始進行排列到某個葉子節點來進行分類的。
(2)葉子節點即為實例所屬的分類的,樹上的每個節點說明了實例的屬性。
(3)樹的生成,開始的所有數據都在根節點上,然后根據你所設定的標準進行分類,用不同的測試屬性遞歸進行數據分析。
決策樹的實現主要思路如下:
(1)先計算整體類別的熵
(2)計算每個特征將訓練數據集分割成的每個子集的熵,并將這個熵乘以每個子集相對于這個訓練集的頻率,最后將這些乘積累加,就會得到一個個特征對應的信息增益。
(3)選擇信息增益最大的作為最優特征分割訓練數據集
(4)遞歸上述過程
(5)遞歸結束條件:訓練集的所有實例屬于同一類;或者所有特征已經使用完畢。
代碼如下:
[python] view plain copy
    #!/usr/bin/python  
    #coding=utf-8  
    import operator  
    import math  
      
    #定義訓練數據集  
    def createDataSet():  
      
        #用書上圖8.2的數據  
        dataSet = [  
                ['youth', 'no', 'no', 'no'],  
                ['youth', 'yes', 'no', 'yes'],  
                ['youth', 'yes', 'yes', 'yes'],  
                ['middle_aged', 'no', 'no', 'no'],  
                ['middle_aged', 'no', 'yes', 'no'],  
                ['senior', 'no', 'excellent', 'yes'],  
                ['senior', 'no', 'fair', 'no']  
        ]  
      
        labels = ['age', 'student', 'credit_rating']  
      
        return dataSet, labels  
      
    #實現熵的計算  
    def calShannonEnt(dataSet):  
      
        numEntries = len(dataSet)  
        labelCounts = {}  
      
        for featVect in dataSet:  
            currentLabel = featVect[-1]  
            if currentLabel not in labelCounts:  
                labelCounts[currentLabel] = 0  
            labelCounts[currentLabel] += 1  
      
        shannonEnt = 0.0  
      
        for key in labelCounts:  
            prob = float(labelCounts[key]) / numEntries  
            shannonEnt -= prob * math.log(prob, 2)  
      
        return  shannonEnt  
      
    #分割訓練數據集  
    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  
      
    #一個確定“最好地”劃分數據元組為個體類的分裂準則的過程  
    def Attribute_selection_method(dataSet):  
      
        numFeatures = len(dataSet[0]) - 1  
        baseEntropy = calShannonEnt(dataSet)  
        bestInfoGain = 0.0  
        bestFeature = -1  
      
        for i in range(numFeatures):  
      
            featList = [example[i] for example in dataSet]  
            uniqueValue = set(featList)  
            newEntropy = 0.0  
      
            for value in uniqueValue:  
                subDataSet = splitDataSet(dataSet, i, value)  
                prob = len(subDataSet) / len(dataSet)  
                newEntropy += prob * calShannonEnt(subDataSet)  
      
            infoGain = baseEntropy - newEntropy  
      
            if infoGain > bestInfoGain:  
                bestInfoGain = infoGain  
                bestFeature = i  
      
        return bestFeature  
      
    #采用majorityvote策略,選擇當前訓練集中實例數最大的類  
    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 Generate_decision_tree(dataSet, labels):  
        classList = [example[-1] for example in dataSet]  
      
        # 訓練集所有實例屬于同一類  
        if classList.count(classList[0]) == len(classList):  
            return classList[0]  
      
        # 訓練集的所有特征使用完畢,當前無特征可用  
        if len(dataSet[0]) == 1:  
            return majorityCnt(classList)  
      
        bestFeat = Attribute_selection_method(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] = Generate_decision_tree(splitDataSet(dataSet, bestFeat, value), subLabels)  
      
        return myTree  
      
    def main():  
        print '  ____            _     _           _____              '  
        print ' |  _ \  ___  ___(_)___(_) ___  _ _|_   _| __ ___  ___ '  
        print '''''   | | | |/ _ \/ __| / __| |/ _ \| '_ \| || '__/ _ \/ _ \\'''  
        print ' | |_| |  __/ (__| \__ \ | (_) | | | | || | |  __/  __/'  
        print ' |____/ \___|\___|_|___/_|\___/|_| |_|_||_|  \___|\___|決策樹'  
        print  
        myDat, labels = createDataSet()  
        myTree = Generate_decision_tree(myDat, labels)  
        print '[*]生成的決策樹:\n',myTree  
      
    if __name__ == '__main__':  
        main() 
這里的數據也是使用書上的(《數據挖掘概念與技術 第三版》)。

運行結果:

數據分析咨詢請掃描二維碼

若不方便掃碼,搜微信號:CDAshujufenxi

數據分析師資訊
更多

OK
客服在線
立即咨詢
日韩人妻系列无码专区视频,先锋高清无码,无码免费视欧非,国精产品一区一区三区无码
客服在線
立即咨詢