美文网首页机器学习机器学习逻辑回归
机器学习-logistic 回归模型

机器学习-logistic 回归模型

作者: 不忘初心的女孩 | 来源:发表于2018-10-05 21:43 被阅读30次

一.logistic回归简介

(sklearn.linear_model模块提供了很多模型供我们使用,比如Logistic回归、Lasso回归、贝叶斯脊回归等)
Logistic回归的主要思想是根据现有的数据对分类边界线建立回归公式,达到分类的目的. “Logistic回归”中的“回归”,数学认为,回归是一个拟合过程,回归分析本质上就是一个函数估计的问题,就是找出因变量和自变量之间的因果关系。具体到例子,假设我们有一些数据点,现在使用一条直线对这些点进行拟合,使得这条线尽可能地表示数据点的分布,这个拟合过程就称作“回归”。机器学习任务中,训练分类器时就是寻找最佳拟合曲线的过程,因此接下来将使用最优化算法。在实现算法之前,先总结Logistic回归的一些属性:

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

二、逻辑回归数学原理

Logistic回归虽然名字里带“回归”,但是它实际上是一种分类方法,主要用于两分类问题(即输出只有两种,分别代表两个类别),所以利用了Sigmoid函数(或称为Logistic函数),函数形式为:
Sigmoid 函数如下图所示 :


image.png 20180316200019693.png

这样我们在原来的线性回归模型外套上sigmoid函数便形成了logistic回归模型的预测函数,可以用于二分类问题:


image.png

对上式的预测函数做一个变换为:


image.png

观察上式可得:若将y视为样本x作为正例的可能性,则1-y便是其反例的可能性。二者的比值便被称为“几率”,反映了x作为正例的相对可能性,这也是logistic回归又被称为对数几率回归的原因!
这里我们也便可以总结一下线性回归模型和logistic回归的关系:
logistic回归分类模型的预测函数是在用线性回归模型的预测值的结果去逼近真实标记的对数几率!这样也便实现了上面说的将线性回归的预测值和分类任务的真实标记联系在了一起!

三.logistic回归算法的代码解析

from numpy import *
import numpy as np
import matplotlib.pyplot as plt
import math

#从文件中加载数据:特征X,标签label
def loadDataSet():
    dataMatrix=[]
    dataLabel=[]
    #这里给出了python 中读取文件的简便方式
    f=open(r'D:\logistic\testSet.txt')
    for line in f.readlines():
        #print(line)
        lineList=line.strip().split()
        dataMatrix.append([1,float(lineList[0]),float(lineList[1])])
        dataLabel.append(int(lineList[2]))
    #for i in range(len(dataMatrix)):
    #   print(dataMatrix[i])
    #print(dataLabel)
    #print(mat(dataLabel).transpose())
    matLabel=mat(dataLabel).transpose()
    return dataMatrix,matLabel

#logistic回归使用了sigmoid函数
def sigmoid(inX):
    # return 1/(1+math.exp(-inX))
    return 1/(1+np.exp(-inX))

#函数中涉及如何将list转化成矩阵的操作:mat()
#同时还含有矩阵的转置操作:transpose()
#还有list和array的shape函数
#在处理矩阵乘法时,要注意的便是维数是否对应

#graAscent函数实现了梯度上升法,隐含了复杂的数学推理
#梯度上升算法,每次参数迭代时都需要遍历整个数据集
def graAscent(dataMatrix,matLabel):
    m,n=shape(dataMatrix)
    matMatrix=mat(dataMatrix)

    w=ones((n,1))#回归系数初始化为1
    alpha=0.001#步长
    num=500#迭代次数
    for i in range(num):
        error=sigmoid(matMatrix*w)-matLabel#误差
        w=w-alpha*matMatrix.transpose()*error
    return w


#随机梯度上升算法的实现,对于数据量较多的情况下计算量小,但分类效果差
#每次参数迭代时通过一个数据进行运算
def stocGraAscent(dataMatrix,matLabel):
    m,n=shape(dataMatrix)
    matMatrix=mat(dataMatrix)

    w=ones((n,1))
    alpha=0.001
    num=20  #这里的这个迭代次数对于分类效果影响很大,很小时分类效果很差
    for i in range(num):
        for j in range(m):
            error=sigmoid(matMatrix[j]*w)-matLabel[j]
            w=w-alpha*matMatrix[j].transpose()*error
    return w

#改进后的随机梯度上升算法
#从两个方面对随机梯度上升算法进行了改进,正确率确实提高了很多
#改进一:对于学习率alpha采用非线性下降的方式使得每次都不一样
#改进二:每次使用一个数据,但是每次随机的选取数据,选过的不在进行选择
def stocGraAscent1(dataMatrix,matLabel):
    m,n=shape(dataMatrix)
    matMatrix=mat(dataMatrix)

    w=ones((n,1))
    num=200  #这里的这个迭代次数对于分类效果影响很大,很小时分类效果很差
    setIndex=set([])#什么意思
    for i in range(num):
        for j in range(m):
            alpha=4/(1+i+j)+0.01

            dataIndex=random.randint(0,100)
            while dataIndex in setIndex:
                setIndex.add(dataIndex)
                dataIndex=random.randint(0,100)
            error=sigmoid(matMatrix[dataIndex]*w)-matLabel[dataIndex]
            w=w-alpha*matMatrix[dataIndex].transpose()*error
    return w

#绘制图像
def draw(weight):
    x0List=[];y0List=[];
    x1List=[];y1List=[];
    f=open(r'D:\logistic\testSet.txt','r')
    for line in f.readlines():
        lineList=line.strip().split()
        if lineList[2]=='0':
            x0List.append(float(lineList[0]))
            y0List.append(float(lineList[1]))
        else:
            x1List.append(float(lineList[0]))
            y1List.append(float(lineList[1]))

    fig=plt.figure()
    ax=fig.add_subplot(111)
    ax.scatter(x0List,y0List,s=10,c='red')
    ax.scatter(x1List,y1List,s=10,c='green')

    xList=[];yList=[]
    x=np.arange(-3,3,0.1)
    for i in np.arange(len(x)):
        xList.append(x[i])

    y=(-weight[0]-weight[1]*x)/weight[2]
    for j in np.arange(y.shape[1]):
        yList.append(y[0,j])

    ax.plot(xList,yList)
    plt.xlabel('x1');plt.ylabel('x2')
    plt.show()


if __name__ == '__main__':
    dataMatrix,matLabel=loadDataSet()
    weight = graAscent(dataMatrix, matLabel)
    weight1=stocGraAscent(dataMatrix, matLabel)
    weight2=stocGraAscent1(dataMatrix,matLabel)
    # print(weight)
    print(weight1)
    # print(weight2)
    # draw(weight)
    draw(weight1)
    # draw(weight2)

上面程序运行结果为:


image.png

其中:
图(1)是使用梯度上升算法的结果,运算复杂度高;
图(2)是使用随机梯度上升算法,分类效果略差吗,运算复杂度低;
图(3)是使用改进后的随机梯度上升算法,分类效果好,运算复杂度低。

2. 回归系数与迭代次数的关系

(代码见logistic3)
可以看到分类效果也是不错的。不过,从这个分类结果中,我们不好看出迭代次数和回归系数的关系,也就不能直观的看到每个回归方法的收敛情况。因此,我们编写程序,绘制出回归系数和迭代次数的关系曲线:

from matplotlib.font_manager import FontProperties
import matplotlib.pyplot as plt
import numpy as np
import random

def loadDataSet():
    dataMat = []                                                        #创建数据列表
    labelMat = []                                                       #创建标签列表
    fr = open(r'D:\logistic\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]))                                 #添加标签
    fr.close()                                                           #关闭文件
    return dataMat, labelMat                                            #返回
def sigmoid(inX):
    return 1.0 / (1 + np.exp(-inX))
def gradAscent(dataMatIn, classLabels):
    dataMatrix = np.mat(dataMatIn)                                        #转换成numpy的mat
    labelMat = np.mat(classLabels).transpose()                            #转换成numpy的mat,并进行转置
    m, n = np.shape(dataMatrix)                                            #返回dataMatrix的大小。m为行数,n为列数。
    alpha = 0.01                                                        #移动步长,也就是学习速率,控制更新的幅度。
    maxCycles = 500                                                        #最大迭代次数
    weights = np.ones((n,1))
    weights_array = np.array([])
    for k in range(maxCycles):
        h = sigmoid(dataMatrix * weights)                                #梯度上升矢量化公式
        error = labelMat - h
        weights = weights + alpha * dataMatrix.transpose() * error
        weights_array = np.append(weights_array,weights)
    weights_array = weights_array.reshape(maxCycles,n)
    return weights.getA(),weights_array                                    #将矩阵转换为数组,并返回

def stocGradAscent1(dataMatrix, classLabels, numIter=150):
    m,n = np.shape(dataMatrix)                                                #返回dataMatrix的大小。m为行数,n为列数。
    weights = np.ones(n)                                                       #参数初始化
    weights_array = np.array([])                                            #存储每次更新的回归系数
    for j in range(numIter):
        dataIndex = list(range(m))
        for i in range(m):
            alpha = 4/(1.0+j+i)+0.01                                            #降低alpha的大小,每次减小1/(j+i)。
            randIndex = int(random.uniform(0,len(dataIndex)))                #随机选取样本
            h = sigmoid(sum(dataMatrix[randIndex]*weights))                    #选择随机选取的一个样本,计算h
            error = classLabels[randIndex] - h                                 #计算误差
            weights = weights + alpha * error * dataMatrix[randIndex]       #更新回归系数
            weights_array = np.append(weights_array,weights,axis=0)         #添加回归系数到数组中
            del(dataIndex[randIndex])                                         #删除已经使用的样本
    weights_array = weights_array.reshape(numIter*m,n)                         #改变维度
    return weights,weights_array                                             #返回

def plotWeights(weights_array1,weights_array2):
    #设置汉字格式
    font = FontProperties(fname=r"C:\Windows\Fonts\simsunb.ttf", size=14)
    #将fig画布分隔成1行1列,不共享x轴和y轴,fig画布的大小为(13,8)
    #当nrow=3,nclos=2时,代表fig画布被分为六个区域,axs[0][0]表示第一行第一列
    fig, axs = plt.subplots(nrows=3, ncols=2,sharex=False, sharey=False, figsize=(20,10))
    x1 = np.arange(0, len(weights_array1), 1)
    #绘制w0与迭代次数的关系
    axs[0][0].plot(x1,weights_array1[:,0])
    axs0_title_text = axs[0][0].set_title(u'梯度上升算法:回归系数与迭代次数关系',FontProperties=font)
    axs0_ylabel_text = axs[0][0].set_ylabel(u'W0',FontProperties=font)
    plt.setp(axs0_title_text, size=20, weight='bold', color='black')
    plt.setp(axs0_ylabel_text, size=20, weight='bold', color='black')
    #绘制w1与迭代次数的关系
    axs[1][0].plot(x1,weights_array1[:,1])
    axs1_ylabel_text = axs[1][0].set_ylabel(u'W1',FontProperties=font)
    plt.setp(axs1_ylabel_text, size=20, weight='bold', color='black')
    #绘制w2与迭代次数的关系
    axs[2][0].plot(x1,weights_array1[:,2])
    axs2_xlabel_text = axs[2][0].set_xlabel(u'迭代次数',FontProperties=font)
    axs2_ylabel_text = axs[2][0].set_ylabel(u'W1',FontProperties=font)
    plt.setp(axs2_xlabel_text, size=20, weight='bold', color='black')
    plt.setp(axs2_ylabel_text, size=20, weight='bold', color='black')


    x2 = np.arange(0, len(weights_array2), 1)
    #绘制w0与迭代次数的关系
    axs[0][1].plot(x2,weights_array2[:,0])
    axs0_title_text = axs[0][1].set_title(u'改进的随机梯度上升算法:回归系数与迭代次数关系',FontProperties=font)
    axs0_ylabel_text = axs[0][1].set_ylabel(u'W0',FontProperties=font)
    plt.setp(axs0_title_text, size=20, weight='bold', color='black')
    plt.setp(axs0_ylabel_text, size=20, weight='bold', color='black')
    #绘制w1与迭代次数的关系
    axs[1][1].plot(x2,weights_array2[:,1])
    axs1_ylabel_text = axs[1][1].set_ylabel(u'W1',FontProperties=font)
    plt.setp(axs1_ylabel_text, size=20, weight='bold', color='black')
    #绘制w2与迭代次数的关系
    axs[2][1].plot(x2,weights_array2[:,2])
    axs2_xlabel_text = axs[2][1].set_xlabel(u'迭代次数',FontProperties=font)
    axs2_ylabel_text = axs[2][1].set_ylabel(u'W1',FontProperties=font)
    plt.setp(axs2_xlabel_text, size=20, weight='bold', color='black')
    plt.setp(axs2_ylabel_text, size=20, weight='bold', color='black')

    plt.show()

if __name__ == '__main__':
    dataMat, labelMat = loadDataSet()
    weights1,weights_array1 = stocGradAscent1(np.array(dataMat), labelMat)

    weights2,weights_array2 = gradAscent(dataMat, labelMat)
    plotWeights(weights_array1, weights_array2)

上面的程序运行结果为:


image.png

由于改进的随机梯度上升算法,随机选取样本点,所以每次的运行结果是不同的。但是大体趋势是一样的。我们改进的随机梯度上升算法收敛效果更好。为什么这么说呢?让我们分析一下。我们一共有100个样本点,改进的随机梯度上升算法迭代次数为150。而上图显示15000次迭代次数的原因是,使用一次样本就更新一下回归系数。因此,迭代150次,相当于更新回归系数150*100=15000次。简而言之,迭代150次,更新1.5万次回归参数。从上图左侧的改进随机梯度上升算法回归效果中可以看出,其实在更新2000次回归系数的时候,已经收敛了。相当于遍历整个数据集20次的时候,回归系数已收敛。训练已完成。

再让我们看看上图右侧的梯度上升算法回归效果,梯度上升算法每次更新回归系数都要遍历整个数据集。从图中可以看出,当迭代次数为300多次的时候,回归系数才收敛。凑个整,就当它在遍历整个数据集300次的时候已经收敛好了。

没有对比就没有伤害,改进的随机梯度上升算法,在遍历数据集的第20次开始收敛。而梯度上升算法,在遍历数据集的第300次才开始收敛。


本文来自 Jack-Cui 的CSDN 博客 ,全文地址请点击:https://blog.csdn.net/c406495762/article/details/77851973?utm_source=copy

四 从疝气病症状预测病马的死亡率

1 实战背景

本次实战内容,将使用Logistic回归来预测患疝气病的马的存活问题。原始数据集下载地址:http://archive.ics.uci.edu/ml/datasets/Horse+Colic

这里的数据包含了368个样本和28个特征。这种病不一定源自马的肠胃问题,其他问题也可能引发马疝病。该数据集中包含了医院检测马疝病的一些指标,有的指标比较主观,有的指标难以测量,例如马的疼痛级别。另外需要说明的是,除了部分指标主观和难以测量外,该数据还存在一个问题,数据集中有30%的值是缺失的。
原始的数据集经过处理,保存为两个文件:horseColicTest.txt和horseColicTraining.txt。已经处理好的“干净”可用的数据集下载地址:

2 使用Python构建Logistic回归分类器

在使用Sklearn构建Logistic回归分类器之前,我们先用自己写的改进的随机梯度上升算法进行预测,先热热身。使用Logistic回归方法进行分类并不需要做很多工作,所需做的只是把测试集上每个特征向量乘以最优化方法得来的回归系数,再将乘积结果求和,最后输入到Sigmoid函数中即可。如果对应的Sigmoid值大于0.5就预测类别标签为1,否则为0。

from numpy import *
import numpy as np
def loadDataSet():
    dataMat=[]
    labelMat=[]
    fr=open(r'D:\logistic\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
def sigmoid(inX):       #Sigmoid函数
    return 1.0/(1+np.exp(-inX))
def gradAscent(dataMatIn,classLabels):  #批量梯度算法
    dataMatrix=mat(dataMatIn)
    labelMat=mat(classLabels).transpose()
    m,n=shape(dataMatrix)
    alpha=0.001
    weights=ones((n,1))
    for k in range(500):
        h=sigmoid(dataMatrix*weights)
        error=labelMat-h
        weights=weights+alpha*dataMatrix.transpose()*error
    return weights
def stocGradAscent(dataMatIn,classLabels):      #随机梯度算法
    m,n=shape(dataMatIn)
    alpha=0.01
    weights=ones(n)
    for i in range(m):
        h=sigmoid(dataMatIn[i]*weights)
        error=(classLabels[i]-h)
        weights=weights+alpha*dataMatIn[i]*error
    return weights
def classifyVector(inX,weights):    #根据概率分类
    prob=sigmoid(sum(inX*weights))
    if prob>0.5:
        return 1.0
    else:
        return 0.0
def colicTest():#打开测试集和训练集,并对数据进行格式化处理
    frTrain=open(r'D:\BaiduNetdiskDownload\机器学习实战源代码\machinelearninginaction\Ch05\horseColicTraining.txt')
    frTest=open(r'D:\BaiduNetdiskDownload\机器学习实战源代码\machinelearninginaction\Ch05\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=gradAscent(np.array(trainingSet),trainingLabels)
    errotcount=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]):
            errotcount+=1
    errorRate=errotcount/numtestvec
    print("error rate--%f"%(float(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)))

if __name__ == '__main__':
    colicTest()
    multiTest()

(错误率的计算选择梯度上升算法和随机梯度上升算法的方法见上面的原博主的链接)
当数据集较小时,我们使用梯度上升算法
当数据集较大时,我们使用改进的随机梯度上升算法

总结

Logistic回归的目的是寻找一个非线性函数sigmoid的最佳拟合参数,求解过程可以由最优化算法来完成。在最优化算法中,最常用的就是梯度上升算法,而梯度上升算法又可以简化为随机梯度上升算法。

随机梯度上升算法和梯度上升算法的效果相当,但占用更少的计算资源。随机梯度上升算法是一种在线算法,可以在数据到来时就完成参数的更新,而不需要重新读取整个数据集来进行批处理运算。

参考资料
logistic回归原理解析及Python应用实例
机器学习之逻辑斯提回归(Logistic Regression)模型
线性回归与逻辑回归
logistic回归的数学推导
机器学习算法总结--线性回归和逻辑回归
Python3《机器学习实战》学习笔记(七):Logistic回归实战篇之预测病马死亡率
《机器学习实战》学习笔记:Logistic回归&预测疝气病证的死亡率

相关文章

网友评论

    本文标题:机器学习-logistic 回归模型

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