In [183]:

 
 
 
 
 
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
    
 
 
In [184]:
 
 
 
 
 
def sigmoid(inX):
    return 1.0/(1+exp(-inX))
 
 
 

批量梯度下降

In [185]:
 
 
 
 
 
def gradAscent(dataMatIn, classLabels):
    dataMatrix = mat(dataMatIn)
    labelMat = mat(classLabels).transpose()
    m,n = shape(dataMatrix)
    alpha = 0.001
    maxCycles = 500
    weights = ones((n,1))
    for k in range(maxCycles):
        h = sigmoid(dataMatrix*weights) #   h是一个矩阵
        error = (labelMat - h)
        weights = weights + alpha * dataMatrix.transpose() * error
    return weights 
 
 
 

随机梯度下降

In [186]:
 
 
 
 
 
def stocGradAscent0(dataMatrix, classLabels):
    m,n = shape(dataMatrix)
    alpha = 0.01
    weights = ones(n)
    #weights = [0.1,0.1,0.1]
    for i in range(m):
        h = sigmoid(sum(dataMatrix[i]*weights))#  h是一个数值
        print dataMatrix[i]
        print weights
        print dataMatrix[i]*weights
        error = classLabels[i] - h
        weights = weights + alpha * error * dataMatrix[i]
    return weights
 
 
 

sum()的参数是一个list 下面是改进的随机梯度上升算法:

In [187]:
 
 
 
 
 
def stocGradAscent1(dataMatrix, classLabels, numIter=150):
    m,n = shape(dataMatrix)
    weights = ones(n)
    #weights = [0.1,0.1,0.1]
    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]*weights))#  h是一个数值
            error = classLabels[randIndex] - h
            weights = weights + alpha * error * dataMatrix[randIndex]
            del(dataIndex[randIndex])
    return weights
 
 
In [188]:
 
 
 
 
 
#import logRegres
 
 
In [189]:
 
 
 
 
 
dataArr,labelMat = loadDataSet()
 
 
In [190]:
 
 
 
 
 
#weights=gradAscent(dataArr,labelMat)
weights=stocGradAscent1(array(dataArr),labelMat,500)
 
 
In [191]:
 
 
 
 
 
def plotBestFit(wei):
    import matplotlib.pyplot as plt
    weights = 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 = (-weights[0]-weights[1]*x)/weights[2]
    ax.plot(x,y)
    plt.xlabel('X1')
    plt.ylabel('X2')
    plt.show()
 
 
 

h = subplot(m,n,p)/subplot(mnp) 将figure划分为m×n块,在第p块创建坐标系,并返回它的句柄。当m,n,p<10时,可以简化为subplot(mnp)或者subplot mnp (注:subplot(m,n,p)或者subplot(mnp)此函数最常用:subplot是将多个图画到一个平面上的工具。其中,m表示是图排成m行,n表示图排成n列,也就是整个figure中有n个图是排成一行的,一共m行,如果第一个数字是2就是表示2行图。p是指你现在要把曲线画到figure中哪个图上,最后一个如果是1表示是从左到右第一个位置。 )

In [192]:
 
 
 
 
 
from numpy import *
#reload
print weights
plotBestFit(weights)

Logistic 回归梯度上升优化函数的更多相关文章

  1. logistic回归梯度上升优化算法

    # Author Qian Chenglong from numpy import * from numpy.ma import arange def loadDataSet(): dataMat = ...

  2. 机器学习——Logistic回归

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

  3. 第五章 Logistic回归

    第五章 Logistic回归 假设现在有一些数据点,我们利用一条直线对这些点进行拟合(该线称为最佳拟合直线),这个拟合过程就称作回归. 为了实现Logistic回归分类器,我们可以在每个特征上都乘以一 ...

  4. 【机器学习实战】第5章 Logistic回归

    第5章 Logistic回归 Logistic 回归 概述 Logistic 回归虽然名字叫回归,但是它是用来做分类的.其主要思想是: 根据现有数据对分类边界线建立回归公式,以此进行分类. 须知概念 ...

  5. 机器学习之Logistic 回归算法

    1 Logistic 回归算法的原理 1.1 需要的数学基础 我在看机器学习实战时对其中的代码非常费解,说好的利用偏导数求最值怎么代码中没有体现啊,就一个简单的式子:θ= θ - α Σ [( hθ( ...

  6. 机器学习笔记(四)Logistic回归模型实现

     一.Logistic回归实现 (一)特征值较少的情况 1. 实验数据 吴恩达<机器学习>第二课时作业提供数据1.判断一个学生能否被一个大学录取,给出的数据集为学生两门课的成绩和是否被录取 ...

  7. 05机器学习实战之Logistic 回归

    Logistic 回归 概述 Logistic 回归 或者叫逻辑回归 虽然名字有回归,但是它是用来做分类的.其主要思想是: 根据现有数据对分类边界线(Decision Boundary)建立回归公式, ...

  8. 机器学习实战(Machine Learning in Action)学习笔记————05.Logistic回归

    机器学习实战(Machine Learning in Action)学习笔记————05.Logistic回归 关键字:Logistic回归.python.源码解析.测试作者:米仓山下时间:2018- ...

  9. 机器学习算法( 五、Logistic回归算法)

    一.概述 这会是激动人心的一章,因为我们将首次接触到最优化算法.仔细想想就会发现,其实我们日常生活中遇到过很多最优化问题,比如如何在最短时间内从A点到达B点?如何投入最少工作量却获得最大的效益?如何设 ...

随机推荐

  1. 青客宝团队Consul内部分享ppt

    青客宝团队Consul内部分享ppt   https://mp.weixin.qq.com/s?src=3&timestamp=1503647705&ver=1&signatu ...

  2. spring cloud 学习(8) - sleuth & zipkin 调用链跟踪

    业务复杂的微服务架构中,往往服务之间的调用关系比较难梳理,一次http请求中,可能涉及到多个服务的调用(eg: service A -> service B -> service C... ...

  3. jQuery 事件方法大全-超全的总结

    jquery经常使用的事件: /*     on     off     hover     blur     change     click     dblclick     focus     ...

  4. 移植Python2到TQ2440

    环境 Python:2.7.13 开发板: TQ2440 工具链: arm-none-linux-gnueabi-gcc 4.8.3 概述 前面已经把Python3移植到TQ2440上面的,现在我们移 ...

  5. 在ASP.NET MVC中使用Knockout实践01,绑定Json对象

    本篇体验在ASP.NET MVC下使用Knockout,将使用EF Code First创建数据库.最后让Knockout绑定一个Json对象. 创建一个领域模型. namespace MvcAppl ...

  6. xcode调试查看变量的值

    对于IPhone开发/XCode的初学者,如何在调试时查看变量的值是很头痛的事情.因为Xcode的expression 经常无法正确显示变量的值.但是强大的GDB可以很方便的帮我们查看变量的值. 当执 ...

  7. 【mysql】sum处理null的结果

    SELECT IFNULL() createSCNum, IFNULL() privateScNum FROM security_code_config WHERE tid = 'test_tenem ...

  8. java解压缩zip和rar的工具类

    package decompress; import java.io.File; import java.io.FileOutputStream; import org.apache.tools.an ...

  9. HttpMessageNotWritableException: Could not write JSON: No serializer found for class ****

    今天碰到一个异常,下面是错误信息 org.springframework.http.converter.HttpMessageNotWritableException: Could not write ...

  10. Android之录音工具类

    /** * 录音工具类 * * @author rendongwei * */ public class RecordUtil { private static final int SAMPLE_RA ...