logistic回归

1.算法思想

根据给定的数据集确定分类的边界。这个分类的边界就是我们所要求的回归函数。

所谓的回归其实就是最佳拟合,回归函数就是确定最佳回归参数,然后对不同的特征赋予不同的权重

2.算法基础

(1)所采用的映射函数是sigmoid函数,sigmoid函数比0-1函数(正方形波)更好的原因是sigmoid函数在局部上看是平滑的,而在全局上看是接近跳跃的。而0-1函数它本身是跳跃的,不够平滑,误差比较大。

(2)根据回归函数计算出了一个结果,然后代入sigmoid函数,就可以得到一个位于0与1之间的函数值,然后根据这个函数值得大小就可以判断类别;如果是二类分类问题值大于0.5属于1类, 否则属于0类

(3)最佳回归系数确定的方法是梯度上升法:

a.梯度上升法是用来求函数的最大值的,常说的梯度下降法是用来求函数的最小值的

b.所谓的梯度其实就是数学中的导数,也就是数据变化最大的方向。一般用倒三角符号来表示梯度。

c.公式为 w= w+ a.tidu(f(w)),其中a是步长,该公式会一直被迭代直到次数达到某一个值,或者达到某个误差允许的范围。

3.算法的优缺点

优点:计算比较简单,易于理解说明

缺点:有可能会欠拟合

适用的数据:标称数据和数值数据

4.算法的python实现
(1)创造简单的数据

from numpy import *
from math import *
import matplotlib.pyplot as plt
# create the data
def createdata(filename):
    fr = open(filename, 'r')
    lines = fr.readlines()
    dataset = []
    labelset = []
    for each in lines:
        current_data = each.strip().split()
        dataset.append([1.0, float(current_data[0]), float(current_data[1])])
        labelset.append(int(current_data[2]))
    return dataset, labelset

(2)定义sigmoid函数

# define the sigmoid fuction
def sigmoid(x):
    return 1.0/(1+ exp(-x))

(3)定义梯度上升算法

# define the gradascent
def gradascent(dataset, lableset):
    datamatrix = mat(dataset)
    y = mat(lableset).transpose()
    m, n = shape(datamatrix)
    a = 0.001
    maxloop = 500
    w = ones((n, 1))
    for i in range(maxloop):
        l = datamatrix*w
        h = ones((m, 1))
        j =0
        for each in l:
            h[j] = sigmoid(each)
            j += 1
        error = y - h
        w += a * datamatrix.transpose()*error
    return w

(4)定义随机梯度下降算法,这是一个改进的算法,之所以它是一个改进的算法是因为他节省了计算资源

# improve the grad
def gradimprove(dataset, datalable, times = 150):
    datamatrix = array(dataset)
    m,n = shape(datamatrix)
    weights = ones(n)
    for i in range(times):
        dataindex = range(m)
        for j in range(m):
            a = 4/(i + j + 10)+0.01
            randindex = int(random.uniform(0, len(dataindex)))
            t = sum(datamatrix[randindex]*weights)
            h = sigmoid(t)
            error = datalable[randindex] - h
            weights += a*datamatrix[randindex]*error
            del(dataindex[randindex])
    return weights

(5)绘制logstic函数

# plot the regression function
def plotregression(weights):
    datamat, datalable = createdata("F:data/machinelearninginaction/Ch05/testSet.txt")
    datastr = array(datamat)
    n = shape(datastr)[0]
    x1 = []
    y1 = []
    x2 = []
    y2 = []
    for i in range(n):
        if datalable[i] == 1:
            x1.append(datastr[i, 1])
            y1.append(datastr[i, 2])
        else:
            x2.append(datastr[i, 1])
            y2.append(datastr[i, 2])
    fig = plt.figure()
    ax = fig.add_subplot(111)
    ax.scatter(x1, y1, s=30, c='red', marker='s')
    ax.scatter(x2, y2, 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.show()

(6)对测试向量进行分类

# classify the vector
def classify(testdata, weights):
    testsum = sum(testdata*weights)
    classnum = sigmoid(testsum)
    if classnum < 0.5:
        return 0
    else:
        return 1

(7)进行十折交叉验证,这里针对的是判定马是否得病的案例

# the multi test
def multitest(times):
    errorall = 0.0
    for i in range(times):
        error = horse()
        errorall += error
    errorrate = errorall/float(times)
    print "the %d errorrate is %f" % (times, errorrate)
    return errorrate

(8)

5.具体应用:判断一匹马是不是得病了

# create the horse function
def horse():
    fr1 = open("F:data/machinelearninginaction/Ch05/horseColicTraining.txt")
    fr2 = open("F:data/machinelearninginaction/Ch05/horseColicTest.txt")
    lines = fr1.readlines()
    dataset = []
    labelset = []
    for each in lines:
        current_data = each.strip().split('\t')
        vector = []
        for i in range(21):
            vector.append(float(current_data[i]))
        dataset.append(vector)
        labelset.append(float(current_data[21]))
    weights = gradimprove(dataset, labelset, 500)
    test_lines = fr2.readlines()
    testdata = []
    testlable = []
    for each in test_lines:
        current_data = each.strip().split('\t')
        vector = []
        for i in range(21):
            vector.append(float(current_data[i]))
        testdata.append(vector)
        testlable.append(float(current_data[21]))
    error = 0.0
    for i in range(len(testdata)):
        lable = classify(testdata[i], weights)
        if lable != testlable[i]:
            error += 1.0
    errorrate = error/float(len(testdata))
    print "the error rate is %f" % errorrate
    return errorrate

5.分析与总结

1.书上的算法采用的是梯度上升算法,但是其实它就是梯度下降算法的变式。因为w = w+(y - h)*X= w-(h-y)*X

2.书上算w为什么没有用到导数的原因见此博客http://blog.csdn.net/dongtingzhizi/article/details/15962797

3.logistic回归,其实就是找到一个能够最好的分割两个类别的边界函数。

logistic 回归的更多相关文章

  1. 神经网络、logistic回归等分类算法简单实现

    最近在github上看到一个很有趣的项目,通过文本训练可以让计算机写出特定风格的文章,有人就专门写了一个小项目生成汪峰风格的歌词.看完后有一些自己的小想法,也想做一个玩儿一玩儿.用到的原理是深度学习里 ...

  2. 机器学习——Logistic回归

    1.基于Logistic回归和Sigmoid函数的分类 2.基于最优化方法的最佳回归系数确定 2.1 梯度上升法 参考:机器学习--梯度下降算法 2.2 训练算法:使用梯度上升找到最佳参数 Logis ...

  3. logistic回归

    logistic回归 回归就是对已知公式的未知参数进行估计.比如已知公式是$y = a*x + b$,未知参数是a和b,利用多真实的(x,y)训练数据对a和b的取值去自动估计.估计的方法是在给定训练样 ...

  4. Logistic回归 python实现

    Logistic回归 算法优缺点: 1.计算代价不高,易于理解和实现2.容易欠拟合,分类精度可能不高3.适用数据类型:数值型和标称型 算法思想: 其实就我的理解来说,logistic回归实际上就是加了 ...

  5. Logistic回归的使用

    Logistic回归的使用和缺失值的处理 从疝气病预测病马的死亡率 数据集: UCI上的数据,368个样本,28个特征 测试方法: 交叉测试 实现细节: 1.数据中因为存在缺失值所以要进行预处理,这点 ...

  6. 如何在R语言中使用Logistic回归模型

    在日常学习或工作中经常会使用线性回归模型对某一事物进行预测,例如预测房价.身高.GDP.学生成绩等,发现这些被预测的变量都属于连续型变量.然而有些情况下,被预测变量可能是二元变量,即成功或失败.流失或 ...

  7. SPSS数据分析—配对Logistic回归模型

    Lofistic回归模型也可以用于配对资料,但是其分析方法和操作方法均与之前介绍的不同,具体表现 在以下几个方面1.每个配对组共有同一个回归参数,也就是说协变量在不同配对组中的作用相同2.常数项随着配 ...

  8. SPSS数据分析—多分类Logistic回归模型

    前面我们说过二分类Logistic回归模型,但分类变量并不只是二分类一种,还有多分类,本次我们介绍当因变量为多分类时的Logistic回归模型. 多分类Logistic回归模型又分为有序多分类Logi ...

  9. SPSS数据分析—二分类Logistic回归模型

    对于分类变量,我们知道通常使用卡方检验,但卡方检验仅能分析因素的作用,无法继续分析其作用大小和方向,并且当因素水平过多时,单元格被划分的越来越细,频数有可能为0,导致结果不准确,最重要的是卡方检验不能 ...

  10. Logistic回归分类算法原理分析与代码实现

    前言 本文将介绍机器学习分类算法中的Logistic回归分类算法并给出伪代码,Python代码实现. (说明:从本文开始,将接触到最优化算法相关的学习.旨在将这些最优化的算法用于训练出一个非线性的函数 ...

随机推荐

  1. 【一天一道LeetCode】#100. Same Tree(100题大关)

    一天一道LeetCode 本系列文章已全部上传至我的github,地址:ZeeCoder's Github 欢迎大家关注我的新浪微博,我的新浪微博 欢迎转载,转载请注明出处 (一)题目 Given t ...

  2. jdbc连接mysql加载驱动程序com.mysql.jdbc.Driver

    在开发环境如eclipse,中加载指定数据库的驱动程序.需要下载MySQL支持JDBC的驱动程序mysql-connector-java-5.1.25-bin.jar. 而具体在Java程序中加载驱动 ...

  3. oracle ebs应用产品安全性-安全性规则

    定义: 通过为段指定包括下限值与上限值的值范围,可以定义安全性规则要素.安全性规则要素适用于包括在指定值范围内的所有段值. 可以将每个安全性规则要素标识为"包括"或"排除 ...

  4. SwipeListView实现仿ios的侧滑

    github地址:https://github.com/xiangzhihong/SwipeMenuListView 今天介绍一个SwipeMenuListView实现侧滑删除的例子,其实和listv ...

  5. 文件I/O实践(1) --基础API

    什么是I/O 输入/输出是内存和外设之间拷贝数据的过程: 设备->内存: 输入操作 内存->设备: 输出操作 高级I/O: ANSI C提供的标准I/O库函数成为高级I/O, 也称为带缓冲 ...

  6. QGIS编译

    一.准备工作 1.下载QGIS源码 最新版本的QGIS源码需要从git上下载.最新的发布版是2.0,下载地址见下.https://github.com/qgis/QGIS/tree/release-2 ...

  7. (七)大图展示Demo引出的UIScrollView的使用

    UIScrollView是一个能够滚动的视图控件,可以通过滚动查看所有内容. 用途: 1.一张大图屏幕放不下,可以用各个方向的手势来看大图的各个部分. 2.手机的设置页面有很多的选项,需要上下滚动来查 ...

  8. Android 数据库框架ormlite

    Android 数据库框架ormlite 使用精要 前言 本篇博客记录一下笔者在实际开发中使用到的一个数据库框架,这个可以让我们快速实现数据库操作,避免频繁手写sql,提高我们的开发效率,减少出错的机 ...

  9. OpenGL下多个sampler在shader中的使用

    在OpenGL中,sampler2D/Cube等做为uniform可以在fragment shader中使用.结合glActiveTexture和glUniform1i,实现texture与sampl ...

  10. 关于Maven中打包命令(项目中打补丁的时候用到)

     打jar包的方式  mvn package -Dmaven.test.skip=true              mvn install -Dmaven.test.skip=true      ...