Logistic回归

算法优缺点:


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

算法思想:

  • 其实就我的理解来说,logistic回归实际上就是加了个sigmoid函数的线性回归,这个sigmoid函数的好处就在于,将结果归到了0到1这个区间里面了,并且sigmoid(0)=0.5,也就是说里面的线性部分的结果大于零小于零就可以直接计算到了。这里的求解方式是梯度上升法,具体我就不扯了,最推荐的资料还是Ng的视频,那里面的梯度下降就是啦,只不过一个是梯度上升的方向一个是下降的方向,做法什么的都一样。
  • 而梯度上升(准确的说叫做“批梯度上升”)的一个缺点就是计算量太大了,每一次迭代都需要把所有的数据算一遍,这样一旦训练集大了之后,那么计算量将非常大,所以这里后面还提出了随机梯度下降,思想就是每次只是根据一个data进行修正。这样得到的最终的结果可能会有所偏差但是速度却提高了很多,而且优化之后的偏差还是很小的。随机梯度上升的另一个好处是这是一个在线算法,可以根据新数据的到来不断处理

函数:

loadDataSet()
创建数据集,这里的数据集就是在一个文件中,这里面有三行,分别是两个特征和一个标签,但是我们在读出的时候还加了X0这个属性
sigmoid(inX)
sigmoid函数的计算,这个函数长这样的,基本坐标大点就和阶跃函数很像了


gradAscend(dataMatIn, classLabels)
梯度上升算法的实现,里面用到了numpy的数组,并且设定了迭代次数500次,然后为了计算速度都采取了矩阵计算,计算的过程中的公式大概是:w= w+alpha*(y-h)x[i](一直懒得写公式,见谅。。。)
gradAscendWithDraw(dataMatIn, classLabels)
上面的函数加强版,增加了一个weight跟着迭代次数的变化曲线
stocGradAscent0(dataMatrix, classLabels)
这里为了加快速度用来随机梯度上升,即每次根据一组数据调整(额,好吧,这个际没有随机因为那是线面那个函数)
stocGradAscentWithDraw0(dataMatrix, classLabels)
上面的函数加强版,增加了一个weight跟着迭代次数的变化曲线
stocGradAscent1(dataMatrix, classLabels, numIter=150)
这就真的开始随机了,随机的主要好处是减少了周期性的波动了。另外这里还加入了alpha的值随迭代变化,这样可以让alpha的值不断的变化,但是都不会减小到0。
stocGradAscentWithDraw1(dataMatrix, classLabels, numIter=150)
上面的函数加强版,增加了一个weight跟着迭代次数的变化曲线
plotBestFit(wei)
根据计算的weight值画出拟合的线,直观观察效果

运行效果分析:
1、梯度上升:
迭代变化趋势

分类结果:
2、随机梯度上升版本1
迭代变化趋势
分类结果:
这个速度虽然快了很多但是效果不太理想啊。不过这个计算量那么少,我们如果把这个迭代200次肯定不一样了,效果如下
果然好多了
3、随机梯度上升版本2
迭代变化趋势
分类结果:
恩,就是这样啦,效果还是不错的啦。代码的画图部分写的有点烂,见谅啦
  1.  #coding=utf-8
    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, labelMat def sigmoid(inX):
    return 1.0/(1+exp(-inX)) def gradAscend(dataMatIn, classLabels):
    dataMatrix = mat(dataMatIn)
    labelMat = mat(classLabels).transpose()
    m,n = shape(dataMatrix)
    alpha = 0.001
    maxCycle = 500
    weight = ones((n,1))
    for k in range(maxCycle):
    h = sigmoid(dataMatrix*weight)
    error = labelMat - h
    weight += alpha * dataMatrix.transpose() * error
    #plotBestFit(weight)
    return weight def gradAscendWithDraw(dataMatIn, classLabels):
    import matplotlib.pyplot as plt
    fig = plt.figure()
    ax = fig.add_subplot(311,ylabel='x0')
    bx = fig.add_subplot(312,ylabel='x1')
    cx = fig.add_subplot(313,ylabel='x2')
    dataMatrix = mat(dataMatIn)
    labelMat = mat(classLabels).transpose()
    m,n = shape(dataMatrix)
    alpha = 0.001
    maxCycle = 500
    weight = ones((n,1))
    wei1 = []
    wei2 = []
    wei3 = []
    for k in range(maxCycle):
    h = sigmoid(dataMatrix*weight)
    error = labelMat - h
    weight += alpha * dataMatrix.transpose() * error
    wei1.extend(weight[0])
    wei2.extend(weight[1])
    wei3.extend(weight[2])
    ax.plot(range(maxCycle), wei1)
    bx.plot(range(maxCycle), wei2)
    cx.plot(range(maxCycle), wei3)
    plt.xlabel('iter_num')
    plt.show()
    return weight def stocGradAscent0(dataMatrix, classLabels):
    m,n = shape(dataMatrix) alpha = 0.001
    weight = ones(n)
    for i in range(m):
    h = sigmoid(sum(dataMatrix[i]*weight))
    error = classLabels[i] - h
    weight = weight + alpha * error * dataMatrix[i]
    return weight def stocGradAscentWithDraw0(dataMatrix, classLabels):
    import matplotlib.pyplot as plt
    fig = plt.figure()
    ax = fig.add_subplot(311,ylabel='x0')
    bx = fig.add_subplot(312,ylabel='x1')
    cx = fig.add_subplot(313,ylabel='x2')
    m,n = shape(dataMatrix) alpha = 0.001
    weight = ones(n)
    wei1 = array([])
    wei2 = array([])
    wei3 = array([])
    numIter = 200
    for j in range(numIter):
    for i in range(m):
    h = sigmoid(sum(dataMatrix[i]*weight))
    error = classLabels[i] - h
    weight = weight + alpha * error * dataMatrix[i]
    wei1 =append(wei1, weight[0])
    wei2 =append(wei2, weight[1])
    wei3 =append(wei3, weight[2])
    ax.plot(array(range(m*numIter)), wei1)
    bx.plot(array(range(m*numIter)), wei2)
    cx.plot(array(range(m*numIter)), wei3)
    plt.xlabel('iter_num')
    plt.show()
    return weight def stocGradAscent1(dataMatrix, classLabels, numIter=150):
    m,n = shape(dataMatrix) #alpha = 0.001
    weight = ones(n)
    for j in range(numIter):
    dataIndex = range(m)
    for i in range(m):
    alpha = 4/ (1.0+j+i) +0.01
    randIndex = int(random.uniform(0,len(dataIndex)))
    h = sigmoid(sum(dataMatrix[randIndex]*weight))
    error = classLabels[randIndex] - h
    weight = weight + alpha * error * dataMatrix[randIndex]
    del(dataIndex[randIndex])
    return weight def stocGradAscentWithDraw1(dataMatrix, classLabels, numIter=150):
    import matplotlib.pyplot as plt
    fig = plt.figure()
    ax = fig.add_subplot(311,ylabel='x0')
    bx = fig.add_subplot(312,ylabel='x1')
    cx = fig.add_subplot(313,ylabel='x2')
    m,n = shape(dataMatrix) #alpha = 0.001
    weight = ones(n)
    wei1 = array([])
    wei2 = array([])
    wei3 = array([])
    for j in range(numIter):
    dataIndex = range(m)
    for i in range(m):
    alpha = 4/ (1.0+j+i) +0.01
    randIndex = int(random.uniform(0,len(dataIndex)))
    h = sigmoid(sum(dataMatrix[randIndex]*weight))
    error = classLabels[randIndex] - h
    weight = weight + alpha * error * dataMatrix[randIndex]
    del(dataIndex[randIndex])
    wei1 =append(wei1, weight[0])
    wei2 =append(wei2, weight[1])
    wei3 =append(wei3, weight[2])
    ax.plot(array(range(len(wei1))), wei1)
    bx.plot(array(range(len(wei2))), wei2)
    cx.plot(array(range(len(wei2))), wei3)
    plt.xlabel('iter_num')
    plt.show()
    return weight def plotBestFit(wei):
    import matplotlib.pyplot as plt
    weight = wei
    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 = (-weight[0] - weight[1]*x)/weight[2]
    ax.plot(x,y)
    plt.xlabel('X1')
    plt.ylabel('X2')
    plt.show() def main():
    dataArr,labelMat = loadDataSet()
    #w = gradAscendWithDraw(dataArr,labelMat)
    w = stocGradAscentWithDraw0(array(dataArr),labelMat)
    plotBestFit(w) if __name__ == '__main__':
    main()

    机器学习笔记索引

Logistic回归 python实现的更多相关文章

  1. Logistic回归python实现

    2017-08-12 Logistic 回归,作为分类器: 分别用了梯度上升,牛顿法来最优化损失函数: # -*- coding: utf-8 -*- ''' function: 实现Logistic ...

  2. Logistic回归python实现小样例

    假设现在有一些点,我们用一条直线对这些点进行拟合(该线称为最佳拟合直线),这个拟合过程就称作回归.利用Logistic回归进行分类的主要思想是:根据现有数据对分类边界线建立回归公式,依次进行分类.Lo ...

  3. 机器学习实战 logistic回归 python代码

    # -*- coding: utf-8 -*- """ Created on Sun Aug 06 15:57:18 2017 @author: mdz "&q ...

  4. logistic回归 python代码实现

    本代码参考自:https://github.com/lawlite19/MachineLearning_Python/blob/master/LogisticRegression/LogisticRe ...

  5. Logistic回归模型和Python实现

    回归分析是研究变量之间定量关系的一种统计学方法,具有广泛的应用. Logistic回归模型 线性回归 先从线性回归模型开始,线性回归是最基本的回归模型,它使用线性函数描述两个变量之间的关系,将连续或离 ...

  6. 【Spark机器学习速成宝典】模型篇02逻辑斯谛回归【Logistic回归】(Python版)

    目录 Logistic回归原理 Logistic回归代码(Spark Python) Logistic回归原理 详见博文:http://www.cnblogs.com/itmorn/p/7890468 ...

  7. 【机器学习速成宝典】模型篇03逻辑斯谛回归【Logistic回归】(Python版)

    目录 一元线性回归.多元线性回归.Logistic回归.广义线性回归.非线性回归的关系 什么是极大似然估计 逻辑斯谛回归(Logistic回归) 多类分类Logistic回归 Python代码(skl ...

  8. 吴裕雄--天生自然python机器学习:使用Logistic回归从疝气病症预测病马的死亡率

    ,除了部分指标主观和难以测量外,该数据还存在一个问题,数据集中有 30%的值是缺失的.下面将首先介绍如何处理数据集中的数据缺失问题,然 后 再 利 用 Logistic回 归 和随机梯度上升算法来预测 ...

  9. 吴裕雄--天生自然python机器学习:Logistic回归

    假设现在有一些数据点,我们用 一条直线对这些点进行拟合(该线称为最佳拟合直线),这个拟合过程就称作回归.利用Logistic回归进行分类的主要思想是:根据现有数据对分类边界线建立回归公式,以此进行分类 ...

随机推荐

  1. Java的多线程机制系列:(一)总述及基础概念

    前言 这一系列多线程的文章,一方面是个人对Java现有的多线程机制的学习和记录,另一方面是希望能给不熟悉Java多线程机制.或有一定基础但理解还不够深的读者一个比较全面的介绍,旨在使读者对Java的多 ...

  2. log4j配置文件加载

    log4j的jar包内部包含preference默认配置,使用者可以通过log4j.xml或log4j.properties来指定自己的配置.xml比properties优先.另外注意java读取pr ...

  3. Zabbix性能优化

    前言 如果不做表分区和删除历史数据规则设置的话,随着时间的推移zabbix的查询性能会变得很低 查看zabbix的性能 通过zabbix的NVPS(每秒处理数值数)来衡量其性能,在zabbix的das ...

  4. oracle中将自建用户下的所有表删除

    select 'drop table '||table_name||' ;' from user_tables;select 'drop sequence '||sequence_name||' ;' ...

  5. Ubuntu学习总结-07 Nodejs和npm的安装

    一 安装NodeJS 1 下载nodejs源码 从以下网址下载最新的Nodejs源码 https://nodejs.org/en/download/ 2 安装依赖的 python,gcc,g++ 函数 ...

  6. JavaScript中的正则表达式(终结篇)

    JavaScript中的正则表达式(终结篇) 在之前的几篇文章中,我们了解了正则表达式的基本语法,但那些语法不是针对于某一个特定语言的.这篇博文我们将通过下面几个部分来了解正则表达式在JavaScri ...

  7. python学习笔记-(十三)堡垒机

    1.课前准备: 本次学习堡垒机相关知识:之前,需要安装Python的paramiko模块,该模块基于SSH用于连接远程服务器并执行相关操作. 前提: python3.5程序安装到默认路径下并已添加pa ...

  8. MathType 6.9 介绍安装

    1.介绍 MathType是强大的数学公式编辑器,与常见的文字处理软件和演示程序配合使用,能够在各种文档中加入复杂的数学公式和符号,可用在编辑数学试卷.书籍.报刊.论文.幻灯演示等方面,是编辑数学资料 ...

  9. 开始学红帽的RHCE课堂有2次课了,要记下自己的学习经历

    我终于申请成功了博客园的博客了. 红帽课堂已经开始2次了,这里的记录可能不分顺序,每天记录一点自己的学习内容.方便自己以后查询. 已经学了以下内容: 1.访问命令行 使用桌面的访问命令 GNOME 3 ...

  10. [linux]Socket编程的头文件

    socket编程中需要用到的头文件 sys/types.h:数据类型定义 sys/socket.h:提供socket函数及数据结构 netinet/in.h:定义数据结构sockaddr_in arp ...