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

熱線電話:13121318867

登錄
首頁精彩閱讀決策樹的python實現(xiàn)方法
決策樹的python實現(xiàn)方法
2018-02-10
收藏

決策樹python實現(xiàn)方法

本文實例講述了決策樹python實現(xiàn)方法。分享給大家供大家參考。具體實現(xiàn)方法如下:

決策樹算法優(yōu)缺點:

優(yōu)點:計算復(fù)雜度不高,輸出結(jié)果易于理解,對中間值缺失不敏感,可以處理不相關(guān)的特征數(shù)據(jù)

缺點:可能會產(chǎn)生過度匹配的問題

適用數(shù)據(jù)類型:數(shù)值型和標(biāo)稱型

算法思想:

1.決策樹構(gòu)造的整體思想:

決策樹說白了就好像是if-else結(jié)構(gòu)一樣,它的結(jié)果就是你要生成這個一個可以從根開始不斷判斷選擇到葉子節(jié)點的樹,但是呢這里的if-else必然不會是讓我們認為去設(shè)置的,我們要做的是提供一種方法,計算機可以根據(jù)這種方法得到我們所需要的決策樹。這個方法的重點就在于如何從這么多的特征中選擇出有價值的,并且按照最好的順序由根到葉選擇。完成了這個我們也就可以遞歸構(gòu)造一個決策樹

2.信息增益

劃分數(shù)據(jù)集的最大原則是將無序的數(shù)據(jù)變得更加有序。既然這又牽涉到信息的有序無序問題,自然要想到想弄的信息熵了。這里我們計算用的也是信息熵(另一種方法是基尼不純度)。公式如下:

數(shù)據(jù)需要滿足的要求:

① 數(shù)據(jù)必須是由列表元素組成的列表,而且所有的列白哦元素都要具有相同的數(shù)據(jù)長度

② 數(shù)據(jù)的最后一列或者每個實例的最后一個元素應(yīng)是當(dāng)前實例的類別標(biāo)簽

函數(shù):

calcShannonEnt(dataSet)

計算數(shù)據(jù)集的香農(nóng)熵,分兩步,第一步計算頻率,第二部根據(jù)公式計算香農(nóng)熵

splitDataSet(dataSet, aixs, value)

劃分數(shù)據(jù)集,將滿足X[aixs]==value的值都劃分到一起,返回一個劃分好的集合(不包括用來劃分的aixs屬性,因為不需要)

chooseBestFeature(dataSet)

選擇最好的屬性進行劃分,思路很簡單就是對每個屬性都劃分下,看哪個好。這里使用到了一個set來選取列表中唯一的元素,這是一中很快的方法

majorityCnt(classList)

因為我們遞歸構(gòu)建決策樹是根據(jù)屬性的消耗進行計算的,所以可能會存在最后屬性用完了,但是分類還是沒有算完,這時候就會采用多數(shù)表決的方式計算節(jié)點分類

createTree(dataSet, labels)

基于遞歸構(gòu)建決策樹。這里的label更多是對于分類特征的名字,為了更好看和后面的理解。

代碼如下:
#coding=utf-8
import operator
from math import log
import time

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

#計算香農(nóng)熵
def calcShannonEnt(dataSet):
    numEntries = len(dataSet)
    labelCounts = {}
    for feaVec in dataSet:
        currentLabel = feaVec[-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 * 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 chooseBestFeatureToSplit(dataSet):
    numFeatures = len(dataSet[0]) - 1#因為數(shù)據(jù)集的最后一項是標(biāo)簽
    baseEntropy = calcShannonEnt(dataSet)
    bestInfoGain = 0.0
    bestFeature = -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
           
#因為我們遞歸構(gòu)建決策樹是根據(jù)屬性的消耗進行計算的,所以可能會存在最后屬性用完了,但是分類
#還是沒有算完,這時候就會采用多數(shù)表決的方式計算節(jié)點分類
def majorityCnt(classList):
    classCount = {}
    for vote in classList:
        if vote not in classCount.keys():
            classCount[vote] = 0
        classCount[vote] += 1
    return max(classCount)        
   
def createTree(dataSet, labels):
    classList = [example[-1] for example in dataSet]
    if classList.count(classList[0]) ==len(classList):#類別相同則停止劃分
        return classList[0]
    if len(dataSet[0]) == 1:#所有特征已經(jīng)用完
        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[:]#為了不改變原始列表的內(nèi)容復(fù)制了一下
        myTree[bestFeatLabel][value] = createTree(splitDataSet(dataSet,
                                        bestFeat, value),subLabels)
    return myTree
   
def main():
    data,label = createDataSet()
    t1 = time.clock()
    myTree = createTree(data,label)
    t2 = time.clock()
    print myTree
    print 'execute for ',t2-t1
if __name__=='__main__':
    main()

希望本文所述對大家的Python程序設(shè)計有所幫助。


數(shù)據(jù)分析咨詢請掃描二維碼

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

數(shù)據(jù)分析師資訊
更多

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(), // 加隨機數(shù)防止緩存 type: "get", dataType: "json", success: function (data) { $('#text').hide(); $('#wait').show(); // 調(diào)用 initGeetest 進行初始化 // 參數(shù)1:配置參數(shù) // 參數(shù)2:回調(diào),回調(diào)的第一個參數(shù)驗證碼對象,之后可以使用它調(diào)用相應(yīng)的接口 initGeetest({ // 以下 4 個配置參數(shù)為必須,不能缺少 gt: data.gt, challenge: data.challenge, offline: !data.success, // 表示用戶后臺檢測極驗服務(wù)器是否宕機 new_captcha: data.new_captcha, // 用于宕機時表示是新驗證碼的宕機 product: "float", // 產(chǎn)品形式,包括:float,popup width: "280px", https: true // 更多配置參數(shù)說明請參見: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); }