利用AdaBoost元演算法提高分類效能

CopperDong發表於2017-10-09

      當做重要決定時,大家可能都會考慮吸取多個專家而不只是一個人的意見,這就是元演算法(meta-algorithm)或者叫整合方法(ensemble method)背後的思路.

      接下來我們將集中關注一個稱作AdaBoost的最流行的元演算法

             優點:泛化錯誤率低,易編碼,可以應用在大部分分類器上,無引數調節

             缺點:對離群點敏感

             適用資料型別:數值型和標稱型資料

一,bagging: 基於資料隨機重抽樣的分類器構建方法

    自舉匯聚法(bootstrap aggregating),也稱為bagging方法,是在從原始資料集選擇S次後得到S個新資料集的一種技術.新資料集和原始資料集的大小相等,允許新資料集中可以有重複的值,而原始資料集的某些值在新集合中則不再出現.

    在S個資料集建好後,將某個學習演算法分別作用於每個資料集就得到了S個分類器.選擇分類器投票結果最多的類別作為最後的分類結果.

    當然,還有一些更先進的bagging方法,比如隨機森林(random forest).

二,boosting

     boosting分類的結果是基於所有分類器的加權求和結果的.    

     bagging中的分類器權重是相等的,而boosting中的分類器權重並不相等

     AdaBoost的一般流程

三,基於單層決策樹構建弱分類器

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 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
>>> import adaboost
>>> datMat,classLabels=adaboost.loadSimpData()
>>> from numpy import *
>>> D = mat(ones((5,1))/5)
>>> adaboost.buildStump(datMat, classLabels, D)
({'dim': 0, 'ineq': 'lt', 'thresh': 1.3}, matrix([[ 0.2]]), array([[-1.],
       [ 1.],
       [-1.],
       [-1.],
       [ 1.]]))

四,完整AdaBoost演算法的實現

虛擬碼:

對每次迭代:

       利用buildStump()函式找到最佳的單層決策樹

       將最佳單層決策樹加入到單層決策樹陣列

       計算alpha

       計算新的權重向量D

       更新累計類別估計值

       如果錯誤率等於0.0, 則退出迴圈

def adaBoostTrainDS(dataArr, classLabels, numIt=40):
	weakClassArr = []
	m = shape(dataArr)[0]
	D = mat(ones((m,1))/m)
	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
>>> reload(adaboost)
<module 'adaboost' from 'adaboost.py'>
>>> classifierArray=adaboost.adaBoostTrainDS(datMat,classLabels,9)
D: [[ 0.2  0.2  0.2  0.2  0.2]]
classEst:  [[-1.  1. -1. -1.  1.]]
aggClassEst:  [[-0.69314718  0.69314718 -0.69314718 -0.69314718  0.69314718]]
total error:  0.2
D: [[ 0.5    0.125  0.125  0.125  0.125]]
classEst:  [[ 1.  1. -1. -1. -1.]]
aggClassEst:  [[ 0.27980789  1.66610226 -1.66610226 -1.66610226 -0.27980789]]
total error:  0.2
D: [[ 0.28571429  0.07142857  0.07142857  0.07142857  0.5       ]]
classEst:  [[ 1.  1.  1.  1.  1.]]
aggClassEst:  [[ 1.17568763  2.56198199 -0.77022252 -0.77022252  0.61607184]]
total error:  0.0
測試演算法

>>> reload(adaboost)
<module 'adaboost' from 'adaboost.py'>
>>> datMat,classLabels=adaboost.loadSimpData()
>>> classifierArray=adaboost.adaBoostTrainDS(datMat,classLabels,30)
>>> adaboost.adaClassify([0,0],classifierArray[0])
[[-0.69314718]]
[[-1.66610226]]
[[-2.56198199]]
matrix([[-1.]])

五,示例: 在一個難資料集上應用AdaBoost

  馬仙病資料集  

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
>>> reload(adaboost)
<module 'adaboost' from 'adaboost.py'>
>>> datArr,labelArr=adaboost.loadDataSet('horseColicTraining2.txt')
>>> classifierArray=adaboost.adaBoostTrainDS(datArr,labelArr,10)
total error:  0.284280936455
total error:  0.284280936455
total error:  0.247491638796
total error:  0.247491638796
total error:  0.254180602007
total error:  0.240802675585
total error:  0.240802675585
total error:  0.220735785953
total error:  0.247491638796
total error:  0.230769230769
>>> testArr,testLabelArr=adaboost.loadDataSet('horseColicTest2.txt')
>>> prediction10 = adaboost.adaClassify(testArr,classifierArray[0])
>>> errArr=mat(ones((67,1)))
>>> errArr[prediction10!=mat(testLabelArr).T].sum()
16.0


  很多人都認為,AdaBoost和SVM是監督機器學習中最強大的兩種方法.實際上,這兩者之間擁有不少相似之處.我們可以把弱分類器想象成SVM中的一個核函式,也可以按照最大化某個最小間隔的方式重寫AdaBoost演算法.而它們的不同就在於其所定義的間隔計算方式有所不同,因此導致的結果也不同.特別是在高維空間下,這兩者之間的差異就會更加明顯.


六,非均衡問題

     效能度量指標:正確率, 召回率及ROC曲線

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
>> reload(adaboost)
>>> classifierArray,aggClassEst=adaboost.adaBoostTrainDS(datArr,labelArr,10)
>>> adaboost.plotROC(aggClassEst.T,labelArr)
the Area Under the Curve is:  0.858296963506




    

相關文章