机器学习实战之Logistic回归

Logistic回归

Logistic回归的一般过程

  • 收集数据:采用任意方法收集数据。
  • 准备数据:由于需要进行距离计算,因此要求数据类型为数值型。另外,结构化数据格式则最佳。
  • 分析数据:采用任意方法对数据进行分析。
  • 训练算法:大部分时间将用于训练,训练的目的是为了找到最佳的分类回归系数。
  • 测试算法:一旦训练步骤完成,分类就会很快。
  • 使用算法:首先,我们输入一些数据,并将其转换成对应的结构化数值;接着,基于训练好的回归系数就可以对这些数值进行简单的回归计算,
    判定他们属于哪个类别;在这之后,我们就可以在输出的类别上做一些其他分析工作。

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

Logistic回归

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

Logistic回归函数
σ ( z ) = 1 1 + e − z \sigma(z)=\frac{1}{1+e^{-z}} σ(z)=1+ez1
为了实现Logistic回归分类器,我们可以在每个特征上都乘以一个回归系数,然后所有的结果值相加,将这个总和带入Sigmoid函数中,得到0~1之间的数值。

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

Sigmoid函数的输入记为z,由下面公式得出:
z = w 0 x 0 + w 1 x 1 + . . . + w n x n z=w_0x_0 + w_1x_1 +...+ w_nx_n z=w0x0+w1x1+...+wnxn,采用向量的写法,可以写为 z = W T X z=W^TX z=WTX
其中向量X是分类器的输入数据,向量W就是我们要找到的最佳参数(系数)。

梯度上升法

梯度算法的思想:
要找到某函数的最大指,最好的方法是沿着该函数的梯度方向探寻。如果梯度记为 ∇ \nabla ,则函数 f ( x , y ) f(x,y) f(x,y)的梯度由下式表示:
∇ f ( x , y ) = ( ∂ f ( x , y ) ∂ x ∂ f ( x , y ) ∂ y ) \nabla f(x,y)=\begin{pmatrix} \frac{\partial f(x,y)}{\partial x} \\ \frac{\partial f(x,y)}{\partial y} \end{pmatrix} f(x,y)=(xf(x,y)yf(x,y))
这个梯度意味着要沿 x x x的方向移动 ∂ f ( x , y ) ∂ x \frac{\partial f(x,y)}{\partial x} xf(x,y),沿 y y y的方向移动 ∂ f ( x , y ) ∂ y \frac{\partial f(x,y)}{\partial y} yf(x,y)
其中函数 f ( x , y ) f(x,y) f(x,y)必须要在待计算的点上有定义并且可微。

在梯度上升算法中,梯度算子总是指向函数值增长最快的方向。用向量来表示的话,梯度上升算法的迭代公式如下:
w : = w + α ∇ w f ( w ) w:=w+\alpha \nabla_w f(w) w:=w+αwf(w),其中 α \alpha α称为步长。
该公式一直被迭代执行,直到达到某个停止条件为止,比如迭代次数达到某个指定值或算法达到某个可以允许的误差范围。

梯度下降法

最经常听到的应该是梯度下降算法,与梯度上升法一样,只是公式中的加法变为减法:
w : = w − α ∇ w f ( w ) w:=w-\alpha \nabla_w f(w) w:=wαwf(w)
梯度上升算法用来求函数的最大值,而梯度下降算法用来求函数的最小值。

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

梯度上升的伪代码如下:

  • 每个回归系数初始化为1
  • 重复R次:
    • 计算整个数据集的梯度
    • 使用alpha * gradient更新回归系数的向量
  • 返回回归系数
# -*- coding: utf-8 -*-
import pandas as pd
import numpy as np
#Logistic回归梯度上升优化算法
fileDir = r'G:\MLinAction\MLiA_SourceCode\machinelearninginaction\Ch05'

#数据获取整理
def loadDataSet():
    dataMat = []
    labelMat = []
    fr = open(fileDir+r'\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))

#gradient 梯度上升算法
def gradAscent(dataMatIn, classLabels):
    dataMatrix = np.mat(dataMatIn)  #将特征值的数据转换为numpy矩阵数据类型
    labelMat = np.mat(classLabels).transpose()  #将分类标签转换为numpy矩阵数据类型并进行转置为列形式
    m, n = np.shape(dataMatrix) #特征值矩阵的行数和列数
    alpha = 0.001   #步长
    maxCycles = 500 #最大循环次数
    weights = np.ones((n,1))    #回归系数初始化为1
    for k in range(maxCycles):
        h = sigmoid(dataMatrix * weights)
        error = (labelMat - h)  #根据weights获得的结果和真实标签值的差
        weights = weights + alpha * dataMatrix.transpose() * error  #迭代更新回归系数weights
    return weights

#函数示例
dataArr,labelMat = loadDataSet()
#weights = gradAscent(dataArr, labelMat)

#画出数据集和Logistic回归最佳拟合直线的函数
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):
        if int(labelMat[i]) == 1:
            xcord1.append(dataArr[i,1]) #将类别为1的第一个特征值赋给xcord1
            ycord1.append(dataArr[i,2]) #将类别为1的第二个特征值赋给ycord1
        else:
            xcord2.append(dataArr[i,1]) #将类别不为1的第一个特征值赋给xcord2
            ycord2.append(dataArr[i,2]) #将类别不为1的第二个特征值赋给ycord2
    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] #最佳拟合直线,分界处为sigmoid函数=0.5,即0=WX,所以w0x0+w1x1+w2x2=0,从而解出x2作为最优直线
    ax.plot(x, y)
    plt.xlabel('X1')
    plt.ylabel('X2')
    plt.show()

训练算法:随机梯度上升

梯度上升算法在每次更新回归系数时都需要遍历整个数据集,导致计算复杂度就太高了。一种改进方法是一次仅用一个样本点来更新回归系数,该方法称为随机梯度上升算法。
随机梯度上升算法伪代码如下:

  • 所有回归系数初始化为1
  • 对数据集中每个样本
    • 计算该样本的梯度
    • 使用alpha * gradient更新回归系数值
  • 返回回归系数值
#随机梯度上升算法
def stocGradAscent0(dataMatrix, classLabels):
    m, n = np.shape(dataMatrix)
    alpha = 0.01
    weights = np.ones(n)
    for i in range(m):
        h = sigmoid(np.sum(dataMatrix[i] * weights))    #一次用一个样本点来计算拟合值
        error = classLabels[i] - h  #得到当前拟合值和对应真实值的误差
        weights = weights + alpha * error * dataMatrix[i]   #一次用一个样本点的结果来计算更新回归系数
    return weights

随机梯度上升算法的优化改进

由于存在一些不能正确分类的样本点(数据集并非线性可分),在每次迭代时会引发系数的剧烈改变,导致在大的波动停止后,还有一些小的周期性波动。

#改进的随机梯度上升算法
def stocGradAscent1(dataMatrix, classLabels, numIter=150):
    m, n = np.shape(dataMatrix)
    weights = np.ones(n)
    for j in range(numIter):
        dataIndex = list(range(m))
        for i in range(m):
            alpha = 4 / (1.0 + j + i) + 0.01    #alpha每次迭代时进行调整
            randIndex = int(np.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
    

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

#利用回归系数计算逻辑回归结果
def classifyVector(inX, weights):
    prob = sigmoid(np.sum(inX * weights))
    if prob > 0.5:
        return 1.0
    else:
        return 0.0

#训练数据&测试数据   
def colicTest():
    frTrain = open(fileDir + r'\horseColicTraining.txt')
    frTest = open(fileDir + r'\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, 500)
    
    #用回归系数对测试数据进行预测,计算误差
    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

#多次训练求平均误差
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))))
 
    
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值