机器学习实战-Logistic回归

来源:互联网 发布:nginx 直播服务器搭建 编辑:程序博客网 时间:2024/06/06 13:10

假设现在有一些数据点,我们用一条直线对这些点进行拟合(该条线路为最佳拟合直线),这条拟合过程就称做回归。
基于Logistic回归和Sigmoid函数的分类

优点:计算代价不高,易于理解和实现
容易欠拟合,分类精度可能不高
适用数据类型:数值型和标称型数据

梯度上升算法的基本思想:要找到某函数的最大值,最好的方法就是沿着该函数的梯度方法搜寻。

#5-1 Logistic回归梯度上升优化算法from numpy import *def loadDataSet():    dataMat = []; labelMat = []    fr = open("testSet.txt")    for line in fr.readlines():        lineArr = line.strip().split()#按空格分        dataMat.append([1.0,float(lineArr[0]),float(lineArr[1])])        labelMat.append(int(lineArr[2]))    return dataMat,labelMatdef sigmoid(inX):    return 1.0/(1+exp(-inX))def gradAscent(dataMatIn,classLabels):    dataMatrix = mat(dataMatIn)    labelMat = mat(classLabels).transpose()#转化为numpy矩阵    m,n = shape(dataMatrix)    alpha = 0.001#步长    maxCycles = 500#迭代次数    weights = ones((n,1))    for k in range(maxCycles):        h = sigmoid(dataMatrix*weights)#列向量        error = (labelMat - h)#真实类别和预测类别的差值        weights = weights + alpha*dataMatrix.transpose()*error    return weights

看看实际效果

import logRegresdataArr,labelMat=logRegres.loadDataSet()logRegres.gradAscent(dataArr,labelMat)Out[70]: matrix([[ 4.12414349],        [ 0.48007329],        [-0.6168482 ]])
#画出决策边界def plotBestFit(weights):    import matplotlib.pyplot as plt    dataMat,labelMat=loadDataSet()    dataArr = array(dataMat)    n = shape(dataArr)[0]    xcord1 = []; ycord1 = []    xcord2 = []; ycord2 = []    for i in range(n):        if int(labelMat[i]) == 1:            xcord1.append(dataArr[i,1]); ycord1.append(dataArr[i,2])        else:            xcord2.append(dataArr[i,1]); ycord2.append(dataArr[i,2])    fig = plt.figure()    ax = fig.add_subplot(111)    ax.scatter(xcord1,ycord1,s=30,c='red',marker="s")    ax.scatter(xcord2,ycord2,s=30,c='green')    x =  arange(-3.0,3.0,0.1)    y = (-weights[0]-weights[1]*x)/weights[2]    ax.plot(x,y)    plt.xlabel('X1');plt.ylabel("X2")    plt.show()
#运行代码import logRegres#dataArr,labelMat=logRegres.loadDataSet()#logRegres.gradAscent(dataArr,labelMat)weights = logRegres.gradAscent(dataArr,labelMat)logRegres.plotBestFit(weights.getA())

梯度上升算法500次迭代

梯度上升算法在每次更新回归系数时,都需要遍历整个数据集,该方法在处理100个左右的数据集时尚可,但如果有数十亿样本和成千上万的特征的时候,那么该算法的时间复杂度就偏高了。一种改进方法就是一次仅使用一个样本点来更新回归系数,该方法称作梯度上升算法:

所有回归系数初始化为1  对数据集中每个样本    计算该样本的梯度    使用alpha*gradient更新回归系数返回回归系数值
5-4随机梯度上升算法def stocGradAscent0(dataMatrix, classLabels):    m,n = shape(dataMatrix)    alpha = 0.01    weights = ones(n)    for i in range(m):        h = sigmoid(sum(dataMatrix))        error = classLabels[i] - h        weights = ones(n)        for i in range(m):            h = sigmoid(sum(dataMatrix[i]*weights))            error = classLabels[i] - h            weights = weights + alpha*error*dataMatrix[i]        return weights

虽然与梯度上升算法有很多相似,但是还是有一些区别:
①后者h和error都是向量,前者都是数值;
②前者没有矩阵的转化过程,所有的变量的数据类型都是NumPy数组

#运行代码from numpy import *import logRegresdataArr,labelMat=logRegres.loadDataSet()weights = logRegres.stocGradAscent0(array(dataArr),labelMat)logRegres.plotBestFit(weights)

随机梯度上升算法,最佳拟合直线并非最佳分类线
但其实结果并不公平,判断一个优化算法优劣的可靠方法是看他是否收敛,也就是说参数是否达到稳定值,是否还会不断的变化。下面我们对程序进行了改进

#5-4 改进的随机梯度上升算法def stocGradAscent1(dataMatrix, classLabels,numIter=150):    m,n = shape(dataMatrix)    weights = ones(n)    for j in range(numIter):        dataIndex = range(m)        for i in range(m):            alpha = 4/(1.0+j+i)+0.0001#每次调整,不会变为0            randIndex = int(random.uniform(0,len(dataIndex)))#随机更新            h = sigmoid(sum(dataMatrix[randIndex]*weights))            error = classLabels[randIndex] - h            weights = weights + alpha*error*dataMatrix[randIndex]            del(dataIndex[randIndex])    return weights
#运行代码from numpy import *import logRegresdataArr,labelMat=logRegres.loadDataSet()weights = logRegres.stocGradAscent1(array(dataArr),labelMat)logRegres.plotBestFit(weights)

改进的随机梯度上升算法

结果和之前图相似,但是计算量更少
默认迭代次数是150,当然也可以修改

weights = logRegres.stocGradAscent1(array(dataArr),labelMat,500)

下面我们尝试从疝气病症预测病马的死亡率,数据包含368 个样本和28个特征。其中30%是缺失的

下面我们开始对数据进行预处理
第一,所有确实值必须使用一个实数值来替代,因为我们使用的NumPy数据类型不允许包含缺失值,这里使用0替代,回归系统的更新公式如下:

weights = weights + alpha*error*dataMatrix[randIndex]

如果dataMatrix的某特征对应值为0,那么该特征的系数将不做更新:、

weights = weights

预处理第二件事就是丢弃已经确实类别标签的数据

处理前数据:http://archive.ics.uci.edu/ml/datasets/Horse+colic/

#5-5def classifyVector(inX,weights):    prob = sigmoid(sum(inX*weights))    if prob > 0.5: return 1.0    else: return 0.0def colicTest():    frTrain = open("horseColicTraining.txt");frTest = open('horseColicTest.txt')    trainingSet = []; trainingLabels = []    for line in frTrain.readlines():        currLine = line.strip().split("\t")        lineArr = []        for i in range(21):            lineArr.append(float(currLine[i]))        trainingSet.append(lineArr)        trainingLabels.append(float(currLine[21]))    trainWeights = stocGradAscent1(array(trainingSet),trainingLabels,1000)    errorCount = 0; numTestVec = 0.0    for line in frTest.readlines():        numTestVec += 1.0        currLine = line.strip().split("\t")        lineArr = []        for i in range(21):            lineArr.append(float(currLine[i]))        if int(classifyVector(array(lineArr),trainWeights))!= int(currLine[21]):            errorCount += 1    errorRate = (float(errorCount)/numTestVec)    print "the error rate of this test is: %f"%errorRate    return errorRatedef multiTest():    numTests = 10; errorSum=0.0    for k in range(numTests):        errorSum += colicTest()    print "after %d iterations the average error rate is: %f" % (numTests, errorSum/float(numTests))
#运行函数from numpy import *import logRegreslogRegres.multiTest()
runfile('E:/上学/机器学习实战/5.最佳回归系数/logRegres-1.py', wdir='E:/上学/机器学习实战/5.最佳回归系数')Reloaded modules: logRegreslogRegres.py:19: RuntimeWarning: overflow encountered in exp  return 1.0/(1+exp(-inX))the error rate of this test is: 0.417910the error rate of this test is: 0.358209the error rate of this test is: 0.298507the error rate of this test is: 0.343284the error rate of this test is: 0.298507the error rate of this test is: 0.417910the error rate of this test is: 0.298507the error rate of this test is: 0.417910the error rate of this test is: 0.417910the error rate of this test is: 0.432836after 10 iterations the average error rate is: 0.370149

最后平均错误率约37%,由于有30%的数据缺失,这个结果还是很乐观的。
随机梯度上升算法与梯度上升算法效果相当,但占用的资源更少,此外,随机梯度上升算法是一个在线算法,它可以在新数据到来时就完成参数更新,而不需要重新读取整个数据集

原创粉丝点击