美文网首页
Logistic回归

Logistic回归

作者: yuanjyyyy | 来源:发表于2018-09-16 13:23 被阅读0次

  • 用一条直线对一些数据点进行拟合(该线称为最佳拟合直线),这个拟合过程就成为回归
  • 利用Logistic回归进行分类的主要思想是:根据现有数据对分类边界建立回归公式,以此进行分类。
  • 训练分类器时的做法是 寻找最佳拟合参数,使用的是 最优化算法。

1 基于Logistic回归和Sigmoid函数的分类

Logistic回归
优点 计算代价不高,易于理解和实现。
缺点 容易欠拟合,分类精度可能不高。
适用数据范围 数值型、标称型。
  • sigmoid函数:σ(z) = 1/(1+e-z)

2 基于最优化方法的最佳回归系数确定

  • z = w0x0+w1x1+w2x2+...+wnxn
  • z = wTx

2.1 梯度上升法

  • 思想:要找到某函数的最大值,最好的方法是沿着该函数的梯度方向探寻。
  • ∇f(x,y) :δf(x,y)/δx;δf(x,y)/δy
  • 梯度上升算法的迭代公式:w := w+α∇wf(w)。α为步长。
  • 梯度下降算法的迭代公式:w := w-α∇wf(w)。α为步长。

2.2 训练算法:使用梯度上升法找到最佳参数

  • 梯度上升法的伪代码
每个回归系数初始化为1
    重复R次:
        计算整个数据集的梯度
        使用alpha * gradient更新回归系数的向量
    返回回归系数
  • 回归系数:确定了不同类别数据之间的分割线。
#初始化数据
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,labelMat

#sigmoid函数
def sigmoid(inX):
    return 1.0/(1+np.exp(-inX))

#梯度上升算法
def gradAscent(dataMatIn, classLabels):
    dataMatrix = np.mat(dataMatIn)             #convert to NumPy matrix
    labelMat = np.mat(classLabels).transpose() #convert to NumPy matrix
    m,n = np.shape(dataMatrix)
    alpha = 0.001
    maxCycles = 500
    weights = np.ones((n,1))
    for k in range(maxCycles):              #heavy on matrix operations
        h = sigmoid(dataMatrix*weights)     #matrix mult
        error = (labelMat - h)              #vector subtraction
        weights = weights + alpha * dataMatrix.transpose()* error #matrix mult
    return weights
  • 测试
import logRegres

dataArr,labelMat = logRegres.loadDataSet()

logRegres.gradAscent(dataArr,labelMat)
Out[16]: 
matrix([[ 4.12414349],
        [ 0.48007329],
        [-0.6168482 ]])
  • weights = weights + alpha * dataMatrix.transpose()* error是在按照真实类别与预测类别的差值方向调整回归系数。

2.3 分析数据:画出决策边界

def plotBestFit(weights):
    import matplotlib.pyplot as plt
    dataMat,labelMat=loadDataSet()
    dataArr = np.array(dataMat)
    n = np.shape(dataArr)[0] 
    xcord1 = []; ycord1 = []
    xcord2 = []; ycord2 = []
    for i in range(n):
        #标签为1类的时候
        if int(labelMat[i])== 1:
            xcord1.append(dataArr[i,1]); ycord1.append(dataArr[i,2])
        #标签为0类的时候
        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 = np.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()
  • 测试
from numpy import *

weights = logRegres.gradAscent(dataArr,LabelMat)

logRegres.plotBestFit(weights.getA())

2.4 训练算法:随机梯度上升

  • 一次仅用一个样本点来更新回归系数。
  • 可以在样本到来时对分类器进行增量学习。
  • 在线学习算法。
  • 与在线学习相对应,一次处理所有数据被称作是“批处理”。
  • 随机梯度上升法的伪代码
所有回归系数初始化为1
对数据集中每个样本
    计算该样本的梯度
    使用alpha*gradient更新回归系数值
返回回归系数值
  • 随机梯度上升算法
def stocGradAscent0(dataMatrix, classLabels):
    m,n = np.shape(dataMatrix)
    alpha = 0.01
    weights = np.ones(n)   #initialize to all ones
    for i in range(m):
        h = sigmoid(sum(dataMatrix[i]*weights))
        error = classLabels[i] - h
        weights = weights + alpha * error * dataMatrix[i]
    return weights
  • 测试
from numpy import *

dataArr,labelMat = logRegres.loadDataSet()

weights = logRegres.stocGradAscent0(array(dataArr),labelMat)

logRegres.plotBestFit(weights)

在stocGradAscent0中,因为数据集并非线性可分,所以在每次迭代时会引发系数的剧烈改变。可以修改为stocGradAscent1。

  • alpha在每次迭代时都会调整,缓解了数据波动或高频波动;虽然alpha会随着迭代次数不断减少,但永远不会减少到0,这是因为alpha = 4/(1.0+j+i)+0.0001中存在一个常数项。必须这样做的原因是为了保证在多次迭代之后更新数据仍然具有一定影响力。
  • 使用了样本随机选择机制,减少周期性波动。
def stocGradAscent1(dataMatrix, classLabels, numIter=150):
    m,n = np.shape(dataMatrix)
    weights = np.ones(n)   #initialize to all ones
    for j in range(numIter):
        dataIndex = list(range(m))
        for i in range(m):
            alpha = 4/(1.0+j+i)+0.0001    #apha decreases with iteration, does not.常数项保证在多次迭代之后更新数据仍然具有一定影响力。
            #减少周期性波动
            randIndex = int(np.random.uniform(0,len(dataIndex)))#go to 0 because of the constant
            h = sigmoid(sum(dataMatrix[randIndex]*weights))
            error = classLabels[randIndex] - h
            weights = weights + alpha * error * dataMatrix[randIndex]
            del(dataIndex[randIndex])
    return weights

3 示例:从疝气病症预测病马的死亡率

3.1 准备数据:处理数据中的缺失值

  • 处理缺失值的方法
  1. 使用可用特征的均值来填补缺失值;
  2. 使用特殊值来填补缺失值,如-1;
  3. 忽略有缺失值的样本;
  4. 使用相似样本的均值填补缺失值;
  5. 使用另外的机器学习算法预测缺失值。
  • logistics缺失值的处理
  1. 所有的缺失值必须用一个实数值来替换,因为我们使用的NumPy数据类型不允许包含缺失值。这里选择实数0来替换所有缺失值恰好能用于logistics回归。
  2. 如果在测试数据集中发现了一条数据的类别标签已经缺失,最简单的就是将该条数据丢弃。

3.2 测试算法:用Logistic回归进行分类

  • 使用logistics回归方法进行分类
  1. 把测试集上每个特征向量乘以最优化方法得来的回归系数;
  2. 将该乘积求和;
  3. 输入到Sigmoid函数在中。
#以回归系数于特征向量作为输入来计算对应的Sigmoid值
def classifyVector(inX, weights):
    prob = sigmoid(sum(inX*weights))
    if prob > 0.5: return 1.0
    else: return 0.0

#用于打开测试集和训练集,并对数据进行格式化处理的函数
def 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(np.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(np.array(lineArr), trainWeights))!= int(currLine[21]):
            errorCount += 1
    errorRate = (float(errorCount)/numTestVec)
    print ("the error rate of this test is: %f" % errorRate)
    return errorRate

#用于调用函数colicTest()10次并求结果的平均值
def 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)))
  • 测试
logRegres.multiTest()
the error rate of this test is: 0.343284
the error rate of this test is: 0.328358
the error rate of this test is: 0.313433
the error rate of this test is: 0.298507
the error rate of this test is: 0.358209
the error rate of this test is: 0.238806
the error rate of this test is: 0.298507
the error rate of this test is: 0.358209
the error rate of this test is: 0.283582
the error rate of this test is: 0.388060
after 10 iterations the average error rate is: 0.320896

相关文章

网友评论

      本文标题:Logistic回归

      本文链接:https://www.haomeiwen.com/subject/ufaxnftx.html