• 机器学习算法-Adaboost


    本章内容

    • 组合类似的分类器来提高分类性能
    • 应用AdaBoost算法
    • 处理非均衡分类问题

    主题:利用AdaBoost元算法提高分类性能

    1.基于数据集多重抽样的分类器

    - AdaBoost
    长处 泛化错误率低,易编码,能够应用在大部分分类器上,无需參数调整
    缺点 对离群点敏感
    适合数据类型 数值型和标称型数据

    bagging:基于数据随机重抽样的分类器构建方法

    自举汇聚法(bootstrap aggregating),也称为bagging方法,是从原始数据集选择S次后得到S个新数据集的一种技术。

    新数据集和原始数据集的大小相等。每一个数据集都是通过在原始数据集中随机选择一个本来进行替换而得到的。

    在S个数据集建好之后,将某个学习算法分别作用域每一个数据集得到了S个分类器。当我们对新数据进行分类时,就能够应用S个分类器进行分类。与此同一时候,选择分类器投票结果最多的类别作为最后的分类结果。

    有一些比較先进的bagging方法,如随机森林(RF)。

    boosting是一种与bagging非常类似的技术。

    不论是boosting还是bagging其中。当使用的多个分类器的类型都是一致的。可是在前者其中,不同的分类器是通过串行训练而获得的。每一个新分类器都依据已训练出的分类器的性能来进行训练。boosting是通过训练集中关注被已有分类器错分的那些数据来获得新的分类器。

    boosting方法有多个版本号,当前最流行便属于AdaBoost

    AdaBoost的一般流程

    (1)收集数据:能够使用不论什么方法;
    (2)准备数据:依赖于所使用的若分类器类型;
    (3)分析数据:能够使用随意方法
    (4)训练算法:AdaBoost的大部分时间都用在训练上,分类器将多次在同一数据集上训练若分类器。
    (5)測试算法:计算分类的错误率;
    (6)使用算法:同SVM一样,AdaBoost预測的两个类别中的一个。假设想要把它应用到多个类的场合,那么就像多类SVM中的做法一样对AdaBoost进行改动。

    2.训练算法:基于错误提升分类器的性能

    AdaBoost是adaptive boosting(自适应boosting)的缩写,其执行过程:训练集中的每一个样本,赋予其一个权重,这些权重构成向量D。一開始,这些权重都初试化成相等值。首先在训练数据上训练处一个若分类器并计算该分类器的错误率,然后在同一数据集上再次训练若分类器。在分类器的第二次训练其中,将会又一次调整每一个样本的权重。其中第一次分队的样本的权重值将会减少。而第一次分错的样本的权重将会提高。

    为了从全部分类器中得到终于的分类结果,AdaBoost为每一个分类器都分配了一个权重值alpha,这些alpha值是基于每一个分类器的错误率进行计算的。其中错误率定义为

    ϵ=

    alpha计算公式

    α=12ln(1ϵϵ)

    计算出alpha值之后,能够对权重向量D进行更新,使得正确分类的样本的权重值减少而分错的样本权重值升高,D的计算方法例如以下
    假设某个样本被正确分类。更新该样本权重值为:

    D(t+1)i=D(t)ieαSum(D)

    假设某个样本被错误分类,更新该样本的权重值为:

    D(t+1)i=D(t)ieαSum(D)

    计算出D后,AdaBoost接着開始下一轮的迭代。AdaBoost算法会不断地反复训练和调整权重的过程,知道训练错误率为0或者若分类器的数目达到用户指定值为止。

    在建立完整的AdaBoost算法之前,须要通过一些代码建立若分类器及保存数据集的权重。

    算法描写叙述:

    Adaboost算法描写叙述

    3.基于单层决策树构建若分类器

    单层决策树是一种简单的决策树。首先构建一个简单的数据集,建立一个adaboost.py文件并增加下列代码:

    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

    导入数据

    >>> import adaboost
    >>> datMat,classLabels=adaboost.loadSimpData()

    附:自适应数据载入函数

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

    以下两个函数,一个用于測试是否某个值小于或者大于我们正在測试的阈值,一个会在一个加权数据集中循环,并找到具有最低错误率的单层决策树。

    伪代码例如以下:

    将最小错误率minError设为无穷大
    对数据及中的每一个特征(第一层循环):
        对每一个步长(第二层循环):
            对每一个不等号(第三层循环):
                建立一颗单层决策树并利用加权数据集对它进行測试
                假设错误率低于minError。则将当前单层决策树设置为最佳单层决策树
    返回最佳单层决策树
    

    单层决策树生成函数代码:

    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
    

    4.AdaBoost算法的实现

    整个实现的伪代码例如以下:

    对每次迭代:
        利用buildStump()函数找到最佳的单层决策树
        将最佳单层决策树增加到单层决策树数据中
        计算alpha
        计算心的权重向量D
        更新累计类别预计值
        假设错误率低于0.0 则退出循环
    

    基于单层决策树的AdaBoost训练过程

    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
    

    5.測试算法

    拥有了多个若分类器以及其相应的alpha值,进行測试就方便了。

    AdaBoost分类函数:利用训练处的多个若分类器进行分类的函数。

    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)

    6.绘制ROC曲线

    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
    

    说明:文章中的代码来自机器学习实战。

    References

    【1】Machine Learning in Action 机器学习实战 第七章



    本栏目Machine Learning持续更新中。欢迎关注:Dream_Angel_Z博客


  • 相关阅读:
    JavaScript window对象之atob()和btoa()
    Flume自定义拦截器
    pySpark提交提交任务到Yarn
    Spark在shell中调试
    从youtube搬视频到B站的方法
    Hbase支持snappy压缩格式
    阵列卡常识
    chrome浏览器插件推荐
    PbootCMS权限管理
    PHP开发规范
  • 原文地址:https://www.cnblogs.com/wzzkaifa/p/7258780.html
Copyright © 2020-2023  润新知