99999久久久久久亚洲,欧美人与禽猛交狂配,高清日韩av在线影院,一个人在线高清免费观看,啦啦啦在线视频免费观看www

熱線電話:13121318867

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

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

引自百度:決策樹算法是一種逼近離散函數值的方法。它是一種典型的分類方法,首先對數據進行處理,利用歸納算法生成可讀的規(guī)則和決策樹,然后使用決策對新數據進行分析。本質上決策樹是通過一系列規(guī)則對數據進行分類的過程
決策樹的算法原理:
(1)通過把實例從根節(jié)點開始進行排列到某個葉子節(jié)點來進行分類的。
(2)葉子節(jié)點即為實例所屬的分類的,樹上的每個節(jié)點說明了實例的屬性。
(3)樹的生成,開始的所有數據都在根節(jié)點上,然后根據你所設定的標準進行分類,用不同的測試屬性遞歸進行數據分析。
決策樹的實現主要思路如下:
(1)先計算整體類別的熵
(2)計算每個特征將訓練數據集分割成的每個子集的熵,并將這個熵乘以每個子集相對于這個訓練集的頻率,最后將這些乘積累加,就會得到一個個特征對應的信息增益。
(3)選擇信息增益最大的作為最優(yōu)特征分割訓練數據集
(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]  
      
    #創(chuàng)建決策樹  
    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
客服在線
立即咨詢
客服在線
立即咨詢
') } function initGt() { var handler = function (captchaObj) { captchaObj.appendTo('#captcha'); captchaObj.onReady(function () { $("#wait").hide(); }).onSuccess(function(){ $('.getcheckcode').removeClass('dis'); $('.getcheckcode').trigger('click'); }); window.captchaObj = captchaObj; }; $('#captcha').show(); $.ajax({ url: "/login/gtstart?t=" + (new Date()).getTime(), // 加隨機數防止緩存 type: "get", dataType: "json", success: function (data) { $('#text').hide(); $('#wait').show(); // 調用 initGeetest 進行初始化 // 參數1:配置參數 // 參數2:回調,回調的第一個參數驗證碼對象,之后可以使用它調用相應的接口 initGeetest({ // 以下 4 個配置參數為必須,不能缺少 gt: data.gt, challenge: data.challenge, offline: !data.success, // 表示用戶后臺檢測極驗服務器是否宕機 new_captcha: data.new_captcha, // 用于宕機時表示是新驗證碼的宕機 product: "float", // 產品形式,包括:float,popup width: "280px", https: true // 更多配置參數說明請參見:http://docs.geetest.com/install/client/web-front/ }, handler); } }); } function codeCutdown() { if(_wait == 0){ //倒計時完成 $(".getcheckcode").removeClass('dis').html("重新獲取"); }else{ $(".getcheckcode").addClass('dis').html("重新獲取("+_wait+"s)"); _wait--; setTimeout(function () { codeCutdown(); },1000); } } function inputValidate(ele,telInput) { var oInput = ele; var inputVal = oInput.val(); var oType = ele.attr('data-type'); var oEtag = $('#etag').val(); var oErr = oInput.closest('.form_box').next('.err_txt'); var empTxt = '請輸入'+oInput.attr('placeholder')+'!'; var errTxt = '請輸入正確的'+oInput.attr('placeholder')+'!'; var pattern; if(inputVal==""){ if(!telInput){ errFun(oErr,empTxt); } return false; }else { switch (oType){ case 'login_mobile': pattern = /^1[3456789]\d{9}$/; if(inputVal.length==11) { $.ajax({ url: '/login/checkmobile', type: "post", dataType: "json", data: { mobile: inputVal, etag: oEtag, page_ur: window.location.href, page_referer: document.referrer }, success: function (data) { } }); } break; case 'login_yzm': pattern = /^\d{6}$/; break; } if(oType=='login_mobile'){ } if(!!validateFun(pattern,inputVal)){ errFun(oErr,'') if(telInput){ $('.getcheckcode').removeClass('dis'); } }else { if(!telInput) { errFun(oErr, errTxt); }else { $('.getcheckcode').addClass('dis'); } return false; } } return true; } function errFun(obj,msg) { obj.html(msg); if(msg==''){ $('.login_submit').removeClass('dis'); }else { $('.login_submit').addClass('dis'); } } function validateFun(pat,val) { return pat.test(val); }