機器學習Python實現AdaBoost

adaboost是boosting方法多個版本中最流行的一個版本,它是通過構建多個弱分類器,通過各個分類器的結果加權之後得到分類結果的。這裏構建多個分類器的過程也是有講究的,通過關注之前構建的分類器錯分的那些數據而獲得新的分類器。這樣的多個分類器在訓練時很容易得到收斂。

本文主要介紹了通過單層決策樹構建弱分類器,同理,也可以用其他的分類算法構建弱分類器。

boost 算法系列的起源來自於PAC Learnability(PAC 可學習性)。這套理論主要研究的是什麼時候一個問題是可被學習的,當然也會探討針對可學習的問題的具體的學習算法。

同時 ,Valiant和 Kearns首次提出了 PAC學習模型中弱學習算法和強學習算法的等價性問題,即任意給定僅比隨機猜測略好的弱學習算法 ,是否可以將其提升爲強學習算法 ? 如果二者等價 ,那麼只需找到一個比隨機猜測略好的弱學習算法就可以將其提升爲強學習算法 ,而不必尋找很難獲得的強學習算法。

PAC 定義了學習算法的強弱

  弱學習算法---識別錯誤率小於1/2(即準確率僅比隨機猜測略高的學習算法)

  強學習算法---識別準確率很高並能在多項式時間內完成的學習算法


在介紹Boost算法的時候先介紹一下boostrapping 和 bagging算法

1)bootstrapping方法的主要過程

  主要步驟:

  i)重複地從一個樣本集合D中採樣n個樣本

  ii)針對每次採樣的子樣本集,進行統計學習,獲得假設Hi

  iii)將若干個假設進行組合,形成最終的假設Hfinal

  iv)將最終的假設用於具體的分類任務

  2)bagging方法的主要過程 -----bagging可以有多種抽取方法

  主要思路:

  i)訓練分類器

  從整體樣本集合中,抽樣n* < N個樣本 針對抽樣的集合訓練分類器Ci

  ii)分類器進行投票,最終的結果是分類器投票的優勝結果

  但是,上述這兩種方法,都只是將分類器進行簡單的組合,實際上,並沒有發揮出分類器組合的威力來。



adaboost算法是可以用任意的弱分類器作爲基礎,這裏的例子主要是通過單層決策樹來實現,這裏的單層決策樹,相對於之前的決策樹而言,簡單了很多,沒有通過計算信息增益之類的方法選取特徵集,而直接利用的是一個三層循環

adaboost全稱是adaptive boosting(自適應boosting),首先,對訓練數據中每一個樣本附上一個權重,這些權重構成向量D,一開始給這些權重初始化爲相同的值。第一次訓練時,權重相同,和原先的訓練方法一樣,訓練結束後,根據訓練的錯誤率,重新分配權重,第一次分對的樣本的權重會降低,分錯的樣本權重會增大,這樣再對第二個分類器進行訓練,每一個分類器都對應一個alpha權重值,這裏的alpha是對於分類器而言,前面的D是對於樣本而言。最後訓練出一系列的弱分類器,對每一個分類器的結果乘以權重值alpha再求和,就是最終的分類結果。自適應就體現在這裏,通過對D的一次次的優化,最後的結果往往可以快速收斂。

這裏錯誤率的定義如下:

錯誤率  =  未正確分類的樣本數 /  總的樣本數

alpha定義如下:


權重D的更新函數如下:

這裏分爲兩種情況

1.該樣本被正確分類:




2.該樣本沒有被正確分類:


這裏的i代表的是第i個樣本,t代表的是第t次訓練。

完整的adaboost算法如下

下面給出一個python實現的例子:

# -*- coding: cp936 -*-
'''
Created on Nov 28, 2010
Adaboost is short for Adaptive Boosting
@author: Peter
'''
from numpy import *

def loadSimpData():
    datMat = matrix([[ 1. ,  2.1],
        [ 2. ,  1.1],
        [ 1.3,  1. ],
        [ 1. ,  1. ],
        [ 2. ,  1. ]])
    classLabels = [1.0, 1.0, -1.0, -1.0, 1.0]
    return datMat,classLabels

def loadDataSet(fileName):      #general function to parse tab -delimited floats
    numFeat = len(open(fileName).readline().split('\t')) #get number of fields 
    dataMat = []; labelMat = []
    fr = open(fileName)
    for line in fr.readlines():
        lineArr =[]
        curLine = line.strip().split('\t')
        for i in range(numFeat-1):
            lineArr.append(float(curLine[i]))
        dataMat.append(lineArr)
        labelMat.append(float(curLine[-1]))
    return dataMat,labelMat

#特徵:dimen,分類的閾值是 threshVal,分類對應的大小值是threshIneq
def stumpClassify(dataMatrix,dimen,threshVal,threshIneq):#just classify the data
    retArray = ones((shape(dataMatrix)[0],1))
    if threshIneq == 'lt':
        retArray[dataMatrix[:,dimen] <= threshVal] = -1.0
    else:
        retArray[dataMatrix[:,dimen] > threshVal] = -1.0
    return retArray
    
#構建一個簡單的單層決策樹,作爲弱分類器
#D作爲每個樣本的權重,作爲最後計算error的時候多項式乘積的作用
#三層循環
#第一層循環,對特徵中的每一個特徵進行循環,選出單層決策樹的劃分特徵
#對步長進行循環,選出閾值
#對大於,小於進行切換

def buildStump(dataArr,classLabels,D):
    dataMatrix = mat(dataArr); labelMat = mat(classLabels).T
    m,n = shape(dataMatrix)
    numSteps = 10.0; bestStump = {}; bestClasEst = mat(zeros((m,1)))  #numSteps作爲迭代這個單層決策樹的步長
    minError = inf #init error sum, to +infinity
    for i in range(n):#loop over all dimensions
        rangeMin = dataMatrix[:,i].min(); rangeMax = dataMatrix[:,i].max();#第i個特徵值的最大最小值
        stepSize = (rangeMax-rangeMin)/numSteps
        for j in range(-1,int(numSteps)+1):#loop over all range in current dimension
            for inequal in ['lt', 'gt']: #go over less than and greater than
                threshVal = (rangeMin + float(j) * stepSize)
                predictedVals = stumpClassify(dataMatrix,i,threshVal,inequal)#call stump classify with i, j, lessThan
                errArr = mat(ones((m,1)))
                errArr[predictedVals == labelMat] = 0
                weightedError = D.T*errArr  #calc total error multiplied by D
                #print "split: dim %d, thresh %.2f, thresh ineqal: %s, the weighted error is %.3f" % (i, threshVal, inequal, weightedError)
                if weightedError < minError:
                    minError = weightedError
                    bestClasEst = predictedVals.copy()
                    bestStump['dim'] = i
                    bestStump['thresh'] = threshVal
                    bestStump['ineq'] = inequal
    return bestStump,minError,bestClasEst

#基於單層決策樹的AdaBoost的訓練過程
#numIt 循環次數,表示構造40個單層決策樹
def adaBoostTrainDS(dataArr,classLabels,numIt=40):
    weakClassArr = []
    m = shape(dataArr)[0]
    D = mat(ones((m,1))/m)   #init D to all equal
    aggClassEst = mat(zeros((m,1)))
    for i in range(numIt):
        bestStump,error,classEst = buildStump(dataArr,classLabels,D)#build Stump
        #print "D:",D.T
        alpha = float(0.5*log((1.0-error)/max(error,1e-16)))#calc alpha, throw in max(error,eps) to account for error=0
        bestStump['alpha'] = alpha  
        weakClassArr.append(bestStump)                  #store Stump Params in Array
        #print "classEst: ",classEst.T
        expon = multiply(-1*alpha*mat(classLabels).T,classEst) #exponent for D calc, getting messy
        D = multiply(D,exp(expon))                              #Calc New D for next iteration
        D = D/D.sum()
        #calc training error of all classifiers, if this is 0 quit for loop early (use break)
        aggClassEst += alpha*classEst
        #print "aggClassEst: ",aggClassEst.T
        aggErrors = multiply(sign(aggClassEst) != mat(classLabels).T,ones((m,1)))  #這裏還用到一個sign函數,主要是將概率可以映射到-1,1的類型
        errorRate = aggErrors.sum()/m
        print "total error: ",errorRate
        if errorRate == 0.0: break
    return weakClassArr,aggClassEst

def adaClassify(datToClass,classifierArr):
    dataMatrix = mat(datToClass)#do stuff similar to last aggClassEst in adaBoostTrainDS
    m = shape(dataMatrix)[0]
    aggClassEst = mat(zeros((m,1)))
    for i in range(len(classifierArr)):
        classEst = stumpClassify(dataMatrix,classifierArr[i]['dim'],\
                                 classifierArr[i]['thresh'],\
                                 classifierArr[i]['ineq'])#call stump classify
        aggClassEst += classifierArr[i]['alpha']*classEst
        print aggClassEst
    return sign(aggClassEst)

def plotROC(predStrengths, classLabels):
    import matplotlib.pyplot as plt
    cur = (1.0,1.0) #cursor
    ySum = 0.0 #variable to calculate AUC
    numPosClas = sum(array(classLabels)==1.0)
    yStep = 1/float(numPosClas); xStep = 1/float(len(classLabels)-numPosClas)
    sortedIndicies = predStrengths.argsort()#get sorted index, it's reverse
    fig = plt.figure()
    fig.clf()
    ax = plt.subplot(111)
    #loop through all the values, drawing a line segment at each point
    for index in sortedIndicies.tolist()[0]:
        if classLabels[index] == 1.0:
            delX = 0; delY = yStep;
        else:
            delX = xStep; delY = 0;
            ySum += cur[1]
        #draw line from cur to (cur[0]-delX,cur[1]-delY)
        ax.plot([cur[0],cur[0]-delX],[cur[1],cur[1]-delY], c='b')
        cur = (cur[0]-delX,cur[1]-delY)
    ax.plot([0,1],[0,1],'b--')
    plt.xlabel('False positive rate'); plt.ylabel('True positive rate')
    plt.title('ROC curve for AdaBoost horse colic detection system')
    ax.axis([0,1,0,1])
    plt.show()
    print "the Area Under the Curve is: ",ySum*xStep


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章