(机器学习实战)第七章

Jupyter Notebook
Untitled
最后检查: 5 小时前
(自动保存)
Current Kernel Logo
Python 3 
File
Edit
View
Insert
Cell
Kernel
Widgets
Help

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
datmat,classlabels = loadSimpData()
datmat
matrix([[1. , 2.1],
        [2. , 1.1],
        [1.3, 1. ],
        [1. , 1. ],
        [2. , 1. ]])
print(type(datmat))
<class 'numpy.matrixlib.defmatrix.matrix'>
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
    
D = mat(ones((5,1))/5)
​
​
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(); 
#         print("rangeMin  :")
#         print(rangeMin)
        rangeMax = dataMatrix[:,i].max();
#         print("rangeMax  :")
#         print(rangeMax)
        stepSize = (rangeMax-rangeMin)/numSteps  # 0.1
        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)  # 0.9   阈值
                predictedVals = stumpClassify(dataMatrix,i,threshVal,inequal)#call stump classify with i, j, lessThan
#                 print("predictedVals = ")
#                 print(predictedVals)
#                 print("dataMatrix = ")
#                 print(dataMatrix)
                errArr = mat(ones((m,1)))
                errArr[predictedVals == labelMat] = 0
#                 print("errArr = ")
#                 print(errArr)
                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()
#                     print("bestClasEst = ")
#                     print(bestClasEst)
                    bestStump['dim'] = i
                    bestStump['thresh'] = threshVal
                    bestStump['ineq'] = inequal
    return bestStump,minError,bestClasEst
​
buildStump(datmat,classlabels,D)
({'dim': 0, 'thresh': 1.3, 'ineq': 'lt'}, matrix([[0.2]]), array([[-1.],
        [ 1.],
        [-1.],
        [-1.],
        [ 1.]]))
​
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
#         print("expon = ")
#         print(expon)
        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
#         print("aggClassEst = ")
#         print(aggClassEst)
#         print("sign(aggClassEst) = ")
#         print(sign(aggClassEst))
#         print("sign(aggClassEst) != mat(classLabels).T = ")
#         print(sign(aggClassEst) != mat(classLabels).T)
        aggErrors = multiply(sign(aggClassEst) != mat(classLabels).T,ones((m,1)))
#         print("aggErrors = ")
#         print(aggErrors)
        errorRate = aggErrors.sum()/m
#         print( "total error: ",errorRate)
        print(errorRate)
        if errorRate == 0.0: break
    return weakClassArr,aggClassEst
​
adaBoostTrainDS(datmat, classlabels, 9)
0.2
0.2
0.0
([{'dim': 0, 'thresh': 1.3, 'ineq': 'lt', 'alpha': 0.6931471805599453},
  {'dim': 1, 'thresh': 1.0, 'ineq': 'lt', 'alpha': 0.9729550745276565},
  {'dim': 0, 'thresh': 0.9, 'ineq': 'lt', 'alpha': 0.8958797346140273}],
 matrix([[ 1.17568763],
         [ 2.56198199],
         [-0.77022252],
         [-0.77022252],
         [ 0.61607184]]))
​
def adaClassify(datToClass,classifierArr):
    dataMatrix = mat(datToClass)#do stuff similar to last aggClassEst in adaBoostTrainDS
#     print("dataMatrix = ")
#     print(dataMatrix)
    m = shape(dataMatrix)[0]
#     print("m = ")
#     print(m)
    aggClassEst = mat(zeros((m,1)))
#     print("aggClassEst = ")
#     print(aggClassEst)
    for i in range(len(classifierArr)):
        classEst = stumpClassify(dataMatrix,classifierArr[i]['dim'],\
                                 classifierArr[i]['thresh'],\
                                 classifierArr[i]['ineq'])#call stump classify
        #print(classEst)
        aggClassEst += classifierArr[i]['alpha']*classEst
        #print (aggClassEst)
    return sign(aggClassEst)
​
classifierArr, aggClassEst = adaBoostTrainDS(datmat, classlabels, 30)
classifierArr
0.2
0.2
0.0
[{'dim': 0, 'thresh': 1.3, 'ineq': 'lt', 'alpha': 0.6931471805599453},
 {'dim': 1, 'thresh': 1.0, 'ineq': 'lt', 'alpha': 0.9729550745276565},
 {'dim': 0, 'thresh': 0.9, 'ineq': 'lt', 'alpha': 0.8958797346140273}]
adaClassify([0,0], classifierArr)
matrix([[-1.]])
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
datArr, labelArr = loadDataSet("horseColicTraining2.txt")
classifierArray,B= adaBoostTrainDS(datArr, labelArr, 10)
classifierArray
0.2842809364548495
0.2842809364548495
0.24749163879598662
0.24749163879598662
0.25418060200668896
0.2408026755852843
0.2408026755852843
0.22073578595317725
0.24749163879598662
0.23076923076923078
[{'dim': 9, 'thresh': 3.0, 'ineq': 'gt', 'alpha': 0.4616623792657674},
 {'dim': 17, 'thresh': 52.5, 'ineq': 'gt', 'alpha': 0.31248245042467104},
 {'dim': 3,
  'thresh': 55.199999999999996,
  'ineq': 'gt',
  'alpha': 0.2868097320169577},
 {'dim': 18,
  'thresh': 62.300000000000004,
  'ineq': 'lt',
  'alpha': 0.23297004638939506},
 {'dim': 10, 'thresh': 0.0, 'ineq': 'lt', 'alpha': 0.19803846151213741},
 {'dim': 5, 'thresh': 2.0, 'ineq': 'gt', 'alpha': 0.18847887349020634},
 {'dim': 12, 'thresh': 1.2, 'ineq': 'lt', 'alpha': 0.15227368997476778},
 {'dim': 7, 'thresh': 1.2, 'ineq': 'gt', 'alpha': 0.15510870821690512},
 {'dim': 5, 'thresh': 0.0, 'ineq': 'lt', 'alpha': 0.13536197353359405},
 {'dim': 4,
  'thresh': 28.799999999999997,
  'ineq': 'lt',
  'alpha': 0.12521587326132078}]
testArr, testLabelArr = loadDataSet("horseColicTest2.txt")
prediction0 = adaClassify(testArr, classifierArray)
#prediction0
​
errArr = mat(ones((67,1)))
#a = prediction0 != mat(testLabelArr).T
errArr[prediction0 != mat(testLabelArr).T].sum() / 67
0.23880597014925373
​
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)
    #print(numPosClas)
    yStep = 1/float(numPosClas); 
    xStep = 1/float(len(classLabels)-numPosClas)
#     print("predStrengths :")
#     print(predStrengths)
    sortedIndicies = predStrengths.argsort()#get sorted index, it's reverse
#     print("sortedIndicies :")
#     print(sortedIndicies)
    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)
​
datArr, labelArr = loadDataSet("horseColicTraining2.txt")
#
classifierArray,aggClassEst = adaBoostTrainDS(datArr, labelArr, 10)
#aggClassEst
0.2842809364548495
0.2842809364548495
0.24749163879598662
0.24749163879598662
0.25418060200668896
0.2408026755852843
0.2408026755852843
0.22073578595317725
0.24749163879598662
0.23076923076923078
plotROC(aggClassEst.T, labelArr)
plotROC(aggClassEst.T, labelArr)

the Area Under the Curve is:  0.8582969635063604
​
​
​

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值