注释:Ng的视频有完整的推到步骤,不过理论和实践还是有很大差别的,代码实现还得完成

1.Logistic回归理论

  http://www.cnblogs.com/wjy-lulu/p/7759515.html,Ng的推导很完美,看懂就可以了,没必要自己推导一遍,因为几天不用就忘记 了。

2.代码实现

  2.1全局梯度上升

    每次训练针对整体,依据整体去找最值。

    好处:容易过滤局部极值,找到真正的全局极值。

    坏处:整体数据太多,花费时间太久,而且新来的样本必须重新训练。

    推倒公式:见博文刚开始的链接,Ng大神的全部推导及证明!

 def loadDataSet():
dataMat = []
labelMat = []
fr = open('testSet.txt')
for line in fr.readlines():
lineArr = line.strip().split()#分割空格
#改变存储data:[[a,b],[c,d]]/
# labels:[1,0,0,1...]
dataMat.append([1.0,float(lineArr[0]),float(lineArr[1])])
labelMat.append([int(lineArr[2])])
return dataMat, labelMat
def sigmoid(intX):
return 1.0/(1.0+np.exp(-intX))
#全局梯度上升法
def gradAscent(dataMatIn,classLabels):
dataMatrix = np.mat(dataMatIn)
labelsMat = np.mat(classLabels)
m, n = dataMatrix.shape
alpha = 0.001
maxCycle = 200
weight = np.ones((n,1))#这里为了简单写,把b也当作一个w了
for k in range(maxCycle):
h = sigmoid(dataMatrix*weight)
error = labelsMat - np.mat(h)
weight = weight + alpha*dataMatrix.transpose()*error
return weight

  2.1简单分类可视化

    利用matplotlib画出简单分类的决策边界

    注意:这里plot转化为list之后绘制的,看网上说可以直接用matrix,但是我运行出错。

 def plotBestFit(weight):
dataMat, labelMat = loadDataSet()
dataArr = np.array(dataMat)#转化为数组
n = dataArr.shape[0]
xcode1=[];ycode1=[]
xcode2=[];ycode2=[]
for i in range(n):
if int(labelMat[i][0])==1:
xcode1.append(dataArr[i,1])
ycode1.append(dataArr[i,2])
else:
xcode2.append(dataArr[i,1])
ycode2.append(dataArr[i,2])
fig = plt.figure("data_x_y")
ax = fig.add_subplot(111)
ax.scatter(xcode1,ycode1,s=30,c='r',marker='s')
ax.scatter(xcode2,ycode2,s=30,c='g')
x = np.mat(np.arange(-3.0,3.0,0.1))
y = (-weight[0]-weight[1]*x)/weight[2]
ax.plot(x.tolist()[0],y.tolist()[0])
plt.xlabel('X1')
plt.ylabel('X2')
plt.show()

  2.3局部随机梯度上升法及改进

    局部随机梯度:和全局相对,利用单个样本更新W,同时又是利用正太分布的规律去随机选择样本的次序。

    好处:‘局部’训练效率高,而且新的样本可以直接添加不用重新训练,‘随机’解决了样本规律性的波动,树上有图解。

    坏处:可能得到局部极值。

 #局部梯度上升法-老版本
def stoGradAscent0(dataMatrix,classLabels):
m,n = dataMatrix.shape
alpha = 0.01
weights = np.ones(n)#最好别写0,因为0的拟合速度很慢
for i in range(m):
h = sigmoid(sum(dataMatrix[i]*weights))
error = classLabels - h
weights = weights +alpha* error* dataMatrix[i]
return weights
#随机梯度上升法-新版本
def stoGradAscent1(dataMatraix,classLabels,numIter=150):
#alpha不断改变
#选取的样本随机改变
m,n = dataMatraix.shape
weights = np.ones(n)
for j in range(numIter):
dataIndex = list(range(m))#样本
for i in range(m):
alpha = 4/(1.0+j+i) +0.01#随着迭代次数和样本的训练次数的增加而减小
randIndex = int(np.random.uniform(0,len(dataIndex)))#随机样本下标
h = sigmoid(sum(dataMatraix[randIndex]*weights))
error = classLabels[randIndex] - h
weights = weights +alpha*error*dataMatraix[randIndex]
del(dataIndex[randIndex])#执行之后删除,避免重复执行
return weights

  2.4实际应用

    和前面朴素贝叶斯都差不多,预处理数据-->>训练-->>测试

 分类函数
def classifyVector(inX,weight):
prob = sigmoid(sum(inX*weight))
if prob>0.5: return 1.0
return 0.0
def colicTest():
frTrain = open('horseColicTraining.txt')
frtest = open('horseColicTest.txt')
trainingSet = []
trainingLabel = []
for line in frTrain.readlines():
currLine = line.strip().split('\t')
lineArr = []
#最后一个是标签
for i in range(len(currLine)-1):
lineArr.append(float(currLine[i]))
trainingSet.append(lineArr)
trainingLabel.append(float(currLine[-1]))
#改进之后的随机梯度下降法--->>>局部算法=在线学习
trainWeight = stoGradAscent1(np.array(trainingSet),trainingLabel,500)
errorCount = 0.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),trainWeight)) != int(currLine[21]):
errorCount+=1
errorRate = (1.0*errorCount)/(1.0*numTestVec)
print('the error Rate is : ',errorRate,'\n')
return errorRate
def multiTest():
numTest = 10;errorSum = 0.0
for k in range(numTest):
errorSum += colicTest()
print('error Rate Average is : ',(errorSum/numTest))

  2.5总程序

 import numpy as np
import matplotlib.pyplot as plt def loadDataSet():
dataMat = []
labelMat = []
fr = open('testSet.txt')
for line in fr.readlines():
lineArr = line.strip().split()#分割空格
#改变存储data:[[a,b],[c,d]]/
# labels:[1,0,0,1...]
dataMat.append([1.0,float(lineArr[0]),float(lineArr[1])])
labelMat.append([int(lineArr[2])])
return dataMat, labelMat
def sigmoid(intX):
return 1.0/(1.0+np.exp(-intX))
#全局梯度上升法
def gradAscent(dataMatIn,classLabels):
dataMatrix = np.mat(dataMatIn)
labelsMat = np.mat(classLabels)
m, n = dataMatrix.shape
alpha = 0.001
maxCycle = 200
weight = np.ones((n,1))#这里为了简单写,把b也当作一个w了
for k in range(maxCycle):
h = sigmoid(dataMatrix*weight)
error = labelsMat - np.mat(h)
weight = weight + alpha*dataMatrix.transpose()*error
return weight def plotBestFit(weight):
dataMat, labelMat = loadDataSet()
dataArr = np.array(dataMat)#转化为数组
n = dataArr.shape[0]
xcode1=[];ycode1=[]
xcode2=[];ycode2=[]
for i in range(n):
if int(labelMat[i][0])==1:
xcode1.append(dataArr[i,1])
ycode1.append(dataArr[i,2])
else:
xcode2.append(dataArr[i,1])
ycode2.append(dataArr[i,2])
fig = plt.figure("data_x_y")
ax = fig.add_subplot(111)
ax.scatter(xcode1,ycode1,s=30,c='r',marker='s')
ax.scatter(xcode2,ycode2,s=30,c='g')
x = np.mat(np.arange(-3.0,3.0,0.1))
y = (-weight[0]-weight[1]*x)/weight[2]
ax.plot(x.tolist()[0],y.tolist()[0])
plt.xlabel('X1')
plt.ylabel('X2')
plt.show()
#局部梯度上升法-老版本
def stoGradAscent0(dataMatrix,classLabels):
m,n = dataMatrix.shape
alpha = 0.01
weights = np.ones(n)#最好别写0,因为0的拟合速度很慢
for i in range(m):
h = sigmoid(sum(dataMatrix[i]*weights))
error = classLabels - h
weights = weights +alpha* error* dataMatrix[i]
return weights
#随机梯度上升法-新版本
def stoGradAscent1(dataMatraix,classLabels,numIter=150):
#alpha不断改变
#选取的样本随机改变
m,n = dataMatraix.shape
weights = np.ones(n)
for j in range(numIter):
dataIndex = list(range(m))#样本
for i in range(m):
alpha = 4/(1.0+j+i) +0.01#随着迭代次数和样本的训练次数的增加而减小
randIndex = int(np.random.uniform(0,len(dataIndex)))#随机样本下标
h = sigmoid(sum(dataMatraix[randIndex]*weights))
error = classLabels[randIndex] - h
weights = weights +alpha*error*dataMatraix[randIndex]
del(dataIndex[randIndex])#执行之后删除,避免重复执行
return weights
#分类函数
def classifyVector(inX,weight):
prob = sigmoid(sum(inX*weight))
if prob>0.5: return 1.0
return 0.0
def colicTest():
frTrain = open('horseColicTraining.txt')
frtest = open('horseColicTest.txt')
trainingSet = []
trainingLabel = []
for line in frTrain.readlines():
currLine = line.strip().split('\t')
lineArr = []
#最后一个是标签
for i in range(len(currLine)-1):
lineArr.append(float(currLine[i]))
trainingSet.append(lineArr)
trainingLabel.append(float(currLine[-1]))
#改进之后的随机梯度下降法--->>>局部算法=在线学习
trainWeight = stoGradAscent1(np.array(trainingSet),trainingLabel,500)
errorCount = 0.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),trainWeight)) != int(currLine[21]):
errorCount+=1
errorRate = (1.0*errorCount)/(1.0*numTestVec)
print('the error Rate is : ',errorRate,'\n')
return errorRate
def multiTest():
numTest = 10;errorSum = 0.0
for k in range(numTest):
errorSum += colicTest()
print('error Rate Average is : ',(errorSum/numTest))

《机器学习实战》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. 剑指offer(1)

    1.二维数组中的查找在一个二维数组中,每一行都按照从左到右递增的顺序排序,每一列都按照从上到下递增的顺序排序.请完成一个函数,输入这样的一个二维数组和一个整数,判断数组中是否含有该整数. public ...

  2. LINUX下PHP网页生成快照(截屏)(xvfb and wkhtmltoimage)

    经测试,可以使用 利用php截屏或实现网页快照我们需要用一个工具:xvfb and wkhtmltoimagek哦,这个工具目前只能在linux系统中使用,下面有兴趣的朋友可进入参考. 在做旅游攻略时 ...

  3. 线程event事件函数实现红绿灯

    #!/usr/bin/env python # -*- coding: utf-8 -*- # author aliex-hrg import threading,time event = threa ...

  4. TdxMemData 的Bug和使用

    aa.CopyFromDataSet(acdsBase);//克隆一个,与LoadFromDataSet区别,如果设置了Field,那么L只会导入设置的部分,而C则是全部复制过来 TdxMemData ...

  5. Maya中输出nuke脚本的方法

    因项目需要,三维部门跟踪组动画组都需要一个能够快速输出nuke预合成工程的脚本.脚本已经写完,源码不便于放出来,写一个大致思路吧. 我首先分析了nuke工程,内部包含了哪些节点,这些节点有哪些属性需要 ...

  6. Android 项目中的资源获取方法

    Android资源文件分类: Android资源文件大致可以分为两种: 第一种是res目录下存放的可编译的资源文件: 这种资源文件系统会在R.java里面自动生成该资源文件的ID,所以访问这种资源文件 ...

  7. 时间序列大数据平台建设(Time Series Data,简称TSD)

    来源:https://blog.csdn.net/bluishglc/article/details/79277455 引言在大数据的生态系统里,时间序列数据(Time Series Data,简称T ...

  8. [LeedCode]279. 完全平方数

    题目描述: 给定正整数 n,找到若干个完全平方数(比如 , , , , ...)使得它们的和等于 n.你需要让组成和的完全平方数的个数最少. 示例 : 输入: n = 输出: 解释: = + + . ...

  9. Linux bash笔记

    关于bash脚本,一般开头都加#!/bin/bash,表示以bash来作为脚本解释器:如果不加的话,就会默认当前用户登陆的shell为脚本解释器(很多情况下为sh,sh与bash不同,有可能导致脚本无 ...

  10. HTTP请求报文

    一个HTTP请求报文,有请求行request line.请求头部header.空行和请求数据组成.看下图可知: 1.请求行 请求行:请求方法.请求地址和协议版本. 请求方法 HTTP/1.1 定义的请 ...