boosting增强学习

来源:互联网 发布:线切割输入编程步骤 编辑:程序博客网 时间:2024/04/30 05:09

boost是通过组合多个弱基学习器,弱学习器定义是泛化性能弱,略优于随机猜测的学习器,通过组合多个若学习器来得到一个强泛化能力的学习器(三个臭皮匠赛过诸葛亮)。

根据单个学习器之间是强依赖以及不能串行序列化的学习代表算法是AdaBoost,另一种相反的方法是Bagging或者随机森林(Random Forest)

adaboost讲解

基本上上面讲解的非常详细,我这里说一点我的理解,boost首先跟决策树没有关系(刚开始理解boost跟决策树有关系),当然有算法有关系但是不是这个,boost其意思是增强,而adaboost是adaptive boosting,既自适应的增强学习。
其核心是一个向前分步算法,AdaBoost算法是向前分步算法的一个特例。我们把一个优化求全局损失函数分解为分步求每一步的损失函数和权重来解决问题。
优点

Adaboost是一种有很高精度的分类器。可以使用各种方法构建子分类器,Adaboost算法提供的是框架。当使用简单分类器时,计算出的结果是可以理解的,并且弱分类器的构造极其简单。简单,不用做特征筛选。不易发生overfitting。

缺点:

对outlier比较敏感

另一种算法Bagging思想更简单,通过对训练集合数据多次采样,而每次采样之后放回,每次采样数据去训练一个基学习器,然后通过多个基学习器线性组合得到一个强学习器,最终结果通过多个基学习器表决产生,而Random forest是基学习器为决策树的Bagging,一般Random forest效果比bagging效果好!,另一个是Random forest可能采样次数很多,同一个样本可能采样多次,而bagging相对较少。
随机森林简单且易于实现,计算开销小,同时性能又很强大,所以用的地方也比较多。

bagging与boosting的区别:

二者的主要区别是取样方式不同。bagging采用均匀取样,而Boosting根据错误率来取样,因此boosting的分类精度要优于Bagging。bagging的训练集的选择是随机的,各轮训练集之间相互独立,而boostlng的各轮训练集的选择与前面各轮的学习结果有关;bagging的各个预测函数没有权重,而boosting是有权重的;bagging的各个预测函数可以并行生成,而boosting的各个预测函数只能顺序生成。对于象神经网络这样极为耗时的学习方法。bagging可通过并行训练节省大量时间开销。

bagging和boosting都可以有效地提高分类的准确性。在大多数数据集中,boosting的准确性比bagging高。在有些数据集中,boosting会引起退化—- Overfit。

Boosting思想的一种改进型AdaBoost方法在邮件过滤、文本分类方面都有很好的性能。

Gradient boosting(又叫Mart, Treenet):Boosting是一种思想,Gradient Boosting是一种实现Boosting的方法,它主要的思想是,每一次建立模型是在之前建立模型损失函数的梯度下降方向。损失函数(loss function)描述的是模型的不靠谱程度,损失函数越大,则说明模型越容易出错。如果我们的模型能够让损失函数持续的下降,则说明我们的模型在不停的改进,而最好的方式就是让损失函数在其梯度(Gradient)的方向上下降。 这个很强大,后面专门开一篇来写。

我这儿写一个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,classLabelsdef 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,labelMatdef 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 retArraydef 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,bestClasEstdef 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,aggClassEstdef 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[0][i]['dim'],classifierArr[0][i]['thresh'],classifierArr[0][i]['ineq'])         aggClassEst += classifierArr[0][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*xStepif __name__ == '__main__':    '''datArr, labelArr = loadDataSet('horseColicTraining2.txt')    classifierArray = adaBoostTrainDS(datArr, labelArr, 10)    print classifierArray    testArr, testLabelArr = loadDataSet('horseColicTest2.txt')    prediction = adaClassify(testArr, classifierArray)    errArr = mat(ones((67, 1)))    print errArr[prediction != mat(testLabelArr).T].sum()    '''    datMat, classLabels = loadSimpData()    classifierArr = adaBoostTrainDS(datMat, classLabels, 30)    print classifierArr    print adaClassify([0, 0], classifierArr)