MachineLearning_AdaBoost

AdaBoost基本原理介绍

一. AdaBoost分类问题

以二分类为例,假设给定一个二类分类的训练数据集 χ = { ( x 1 , y 1 ) , ( x 2 , y 2 ) , . . . , ( x n , y n ) } \chi = \left \{ (x_{1}, y_{1}), (x_{2}, y_{2}),...,(x_{n}, y_{n})\right \}, 其中 x i x_{i} 表示样本点, y i y_{i} 表示样本对应的类别,其可取值为{-1,1}。AdaBoost算法利用如下的算法,从训练数据中串行的学习一系列的弱学习器,并将这些弱学习器线性组合为一个强学习器。AdaBoost算法描述如下:
输入:训练数据集 χ = { ( x 1 , y 1 ) , ( x 2 , y 2 ) , . . . , ( x n , y n ) } \chi = \left \{ (x_{1}, y_{1}), (x_{2}, y_{2}),...,(x_{n}, y_{n})\right \}

输出:最终的强分类器G(x)

(1) 初始化训练数据的权重分布值:( D m D_m 表示第m个弱学习器的样本点的权值N为样本总数)
D 1 = ( w 11 , . . . , w 1 i , . . . , w 1 N ) , w 1 i = 1 / N , i = 1 , 2 , . . . , N D_{1}=(w_{11},...,w_{1i},...,w_{1N}), w_{1i}=1/N, i=1,2,...,N

(2) 对M个弱学习器,m=1,2,…,M:

(a)使用具有权值分布 D m D_m 的训练数据集进行学习,得到基本分类器 G m ( x ) G_m(x) ,其输出值为{-1,1};
(b)计算弱分类器在训练数据集上的分类误差率,其值越小的基分类器在最终分类器中的作用越大。
e m = P ( G m ( x i ) y i ) = e_m=P(G_m(x_i)\neq y_i)=
i = 1 N w m i I ( G m ( x i ) y i ) \displaystyle \sum^{N}_{i=1}{w_{mi}I(G_m(x_i)\neq y_i)}
其中, I ( G m ( x i ) y i ) I(G{_{m}}(x{_{i}})\neq y{_{i}}) 取值为0或1,取0表示分类正确,取1表示分类错误。
(c)计算弱分类器 G m ( x ) G{_{m}}(x) 的权重系数 α m \alpha {_{m}} :(这里的对数是自然对数)

α m = 1 2 l n 1 e m e m \alpha {_{m}}=\frac{1}{2}ln{\frac{1-e{_{m}}}{e{_{m}}}}
一般情况下 e m e_m 的取值应该小于0.5,因为若不进行学习随机分类的话,由于是二分类错误率等于0.5,当进行学习的时候,错误率应该略低于0.5。当 c m c_m 减小的时候 α m \alpha_m 的值增大,而我们希望得到的是分类误差率越小的弱分类器的权值越大,对最终的预测产生的影响也就越大,所以将弱分类器的权值设为该方程式从直观上来说是合理地,具体的证明 a l p h a m alpha_m 为上式请继续往下读。
(d)更新训练数据集的样本权值分布:
D m + 1 = ( w m + 1 , 1 , w m + 1 , 2 . . . w m + 1 , i . . . , w m + 1 , N ) , w m + 1 , i = w m i Z m e x p ( α m y i G m ( x i ) ) , i = 1 , 2 , . . . N D_{m+1}=(w_{m+1,1},w_{m+1,2}...w_{m+1,i}...,w_{m+1,N}),\\ w_{m+1,i}=\frac{w_{mi}}{Z_m}exp(-\alpha_my_iG_m(x_i)), i=1, 2, ...N
对于二分类,弱分类器 G m ( x ) G{_{m}}(x) 的输出值取值为{-1,1}, y i y{_{i}} 的取值为{-1,1},所以对于正确的分类 y i G m ( x ) y{_{i}}G{_{m}}(x) >0,对于错误的分类 y i G m ( x ) y{_{i}}G{_{m}}(x) <0,由于样本权重值在[0,1]之间,当分类正确时 w m + 1 , i w{_{m+1,i}} 取值较小,而分类错误时 w m + 1 , i w{_{m+1,i}} 取值较大,而我们希望得到的是权重值高的训练样本点在后面的弱学习器中会得到更多的重视,所以该上式从直观上感觉也是合理地,具体怎样合理,请往下读。
其中, Z m Z{_{m}} 是规范化因子,主要作用是将 W m i W{_{mi}} 的值规范到0-1之间,使得 i = 1 N W m i \displaystyle \sum_{i=1}^{N}{W{_{mi}}} = 1。

Z m = i = 1 N w m i e x p ( α m y i G m ( x i ) ) Z_m=\displaystyle \sum_{i=1}^{N}w_{mi}exp(-\alpha_my_iG_m(x_i))

(3) 上面我们介绍了弱学习器的权重系数α如何计算,样本的权重系数W如何更新,学习的误差率e如何计算,接下来是最后一个问题,各个弱学习器采用何种结合策略了,AdaBoost对于分类问题的结合策略是加权平均法。如下,利用加权平均法构建基本分类器的线性组合:
f ( x ) = m = 1 M α m G M ( x ) f(x) = \displaystyle \sum_{m=1}^M \alpha_mG_M(x)
得到最终的分类器:
G ( x ) = s i g n ( f ( x ) ) = s i g n ( m = 1 M α m G m ( x ) ) G(x)=sign(f(x))=sign(\displaystyle \sum_{m=1}^M\alpha_mG_m(x))
以上就是对于AdaBoost分类问题的介绍,接下来是对AdaBoost的回归问题的介绍。

二.AdaBoost回归问题

AdaBoost回归问题有许多变种,这里我们以AdaBoost R2算法为准。

(1)我们先看看回归问题的误差率问题,对于第m个弱学习器,计算他在训练集上的最大误差:
E m = m a x y i G m ( x i ) i = 1 , 2 , . . . , N E_m=max|y_i-G_m(x_i)|\quad i=1,2,...,N
然后计算每个样本的相对误差:(计算相对误差的目的是将误差规范化到[0,1]之间)
e m i = y i G m ( x i ) E m , 0 e m i 1 e_{mi}=\frac{|y_i-G_m(x_i)|}{E_m}, \quad 显然0 \leq e_{mi}\leq1
这里是误差损失为线性时的情况,如果我们用平方误差,则 e m i = y i G m ( x i ) E m 2 2 e{_{mi}}=\frac{|y{_{i}}-G{_{m}}(x{_{i}})|}{E{_{m}}^2}^2 ,如果我们用指数误差,则 e m i = 1 e x p ( y i + G m ( x i ) E m ) e{_{mi}}=1-exp(\frac{-y{_{i}}+G{_{m}}(x{_{i}})}{E{_{m}}})

最终得到第k个弱学习器的误差率为:
e m = i = 1 N w m i e m i e{_{m}}=\sum_{i=1}^{N}{w{_{mi}}e{_{mi}}} ,表示每个样本点的加权误差的总和即为该弱学习器的误差。

(2)我们再来看看弱学习器的权重系数α,如下公式:
α m = e m 1 e m \alpha_m=\frac{e_m}{1-e_m}
(3)对于如何更新回归问题的样本权重,第k+1个弱学习器的样本权重系数为:
w m 1 , i = w m i Z m α m 1 e m w_{m_1,i}=\frac{w_{mi}}{Z_m}\alpha_m^{1-e_m}
其中Z{_{k}}是规范化因子: Z m = i = 1 N w m i α m 1 e m i Z{_{m}}=\sum_{i=1}^{N}{w{_{mi}}\alpha {_{m}}^{1-e{_{mi}}}}
(4)最后是结合策略,和分类问题不同,回归问题的结合策略采用的是对加权弱学习器取中位数的方法,最终的强回归器为:
G ( x ) = m = 1 M g ( x ) l n 1 α m G(x)=\sum_{m=1}^{M}{g(x)ln\frac{1}{\alpha {_{m}}}} ,其中 g ( x ) g(x) 是所有 α m G m ( x ) \alpha {_{m}}G{_{m}}(x) 的中位数(m=1,2,…,M)。
这就是AdaBoost回归问题的算法介绍。

代码实现

'''
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

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
    

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)))
    minError = inf #init error sum, to +infinity
    for i in range(n):#loop over all dimensions
        rangeMin = dataMatrix[:,i].min(); rangeMax = dataMatrix[:,i].max();
        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


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)))
        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
发布了100 篇原创文章 · 获赞 10 · 访问量 3414

猜你喜欢

转载自blog.csdn.net/qq_44315987/article/details/103537754
今日推荐