机器学习实战--adaboost

前面我们已经学了好几个分类算法了(svm后面再讲),分类效果也还不错,但是我们也许会想,能不能在一个数据集上多次应用同一个算法,或者应用不同的算法呢?这就是我们adaboost的思想:通过多个弱分类器的组合,构成一个强分类器。
算法优点:
泛化错误率低,易编码,可应用在大部分分类器上,无需参数的调整
算法缺点:
对离群点很敏感
算法步骤:
这里我们用多个单层分类决策树为例(buildStump)
对每次循环:
1、用buildStump找到最佳的单层决策树
2、将最佳单层决策树加入到单层决策树数组
3、根据分类错误率计算新的(单层决策树)分类器权重alpha
4、计算新的权重向量(对每个样本)D
5、检查错误率是否小于指定值,若是,跳出循环,否则继续循环,直到循环次数满,或满足5中的条件
主要算法代码:
1、构建单层决策树,每个决策树用字典保存,D为每个样本的权重向量,决策树分错的样本,对应的权重越大。

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

2、训练决策树,numIt为循环次数,构建好的多个决策树用列表保存,aggClassEst 用来保存累计的分类值(和分类器的权重有关),aggErrors = multiply(sign(aggClassEst) != mat(classLabels).T,ones((m,1)))这个代码用的很巧妙,要多学习,另外对于multiply函数而言,矩阵和数组,数组和数组,等..之间都可以进行运算。

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

3、分类

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)

注意事项:
1、增加循环次数numIt,我们会发现在训练数据集上的错误率会越来越低,但在测试数据集上的错误率会先下降后上升,即出现了所谓的“过拟合”,也有理论说,如果数据集选得足够好的话,不会出现上面的问题,看来我们选的数据集还不够理想。
2、如果想在一个数据集上运用多个算法,该怎么改进上述算法?只需将一直使用一种分类器改为多种分类器交叉使用,得到分类后的结果,即可进行alpha和D的更新,并注意数据的接口要一致。
3、非均衡分类问题。作为对前述分类器的讨论,前述分类器中,我们并没有考虑分错的代价,为了研究这些关系,我么引入正确率,召回率,ROC曲线,AUC。这里给出ROC曲线和AUC的计算源码。对于代价问题,我们一样的可以引入不同的权重加以解决。非均衡问题亦可通过数据抽样加以改善(过抽样,欠抽样)

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

你可能感兴趣的:(机器学习,机器学习,算法,adaboost)