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. IntraWeb XIV 类型速查表

    tkClass ================== IWUserSessionBase.TIWUserSessionBase < TDataModule < TComponent < ...

  2. LayoutInflater作用及使用(转)

    作用: 1.对于一个没有被载入或者想要动态载入的界面, 都需要使用inflate来载入. 2.对于一个已经载入的Activity, 就可以使用实现了这个Activiyt的的findViewById方法 ...

  3. 在Ubuntu的系统中怎样将应用程序加入到開始菜单中

    /*********************************************************************  * Author  : Samson  * Date   ...

  4. TimingTool - The Timing Diagram Editor

    TimingTool - The Timing Diagram TimingTool is designed to give electronics engineers an easy to use ...

  5. lodoop打印控件详解

    注意:使用此打印控件需要引入(在我上传的Demo中都有): install_lodop32.exe install_lodop64.exe LodopFuncs.js jquery-1.10.0.mi ...

  6. latex编写论文

    写给像我这样需要使用latex编写论文的小菜鸟,给出demo和注释,高级部分自己参透(默认你已经搭好环境). 1.搭论文架子 demo1 \documentclass[10pt,a4paper]{ar ...

  7. [Winfrom]Cefsharp配置与初始化

    摘要 在做客户端程序的时候,本来打算使用wpf的,但在内嵌cefsharp的时候,发现输入法有问题,所以使用了winform作为cefsharp的容器. 系列文章 CefSharp 在同一窗口打开链接 ...

  8. Spark RDD的fold和aggregate为什么是两个API?为什么不是一个foldLeft?

    欢迎关注我的新博客地址:http://cuipengfei.me/blog/2014/10/31/spark-fold-aggregate-why-not-foldleft/ 大家都知道Scala标准 ...

  9. Android的学习之路(三)项目的启动过程和安装过程具体解释

    应用的安装和启动过程: 安装:第一步:java的编译器会把这个.java文件编译成.class文件           第二部:Android的SDK提供了一个dx工具,这个工具把.class文件转义 ...

  10. Warning: The Copy Bundle Resources build phase contains this target's Info.plist file 'Info

    WARNING: The Copy Bundle Resources build phase contains this target's Info.plist file 'Info.plist'. ...