python编写Logistic逻辑回归


Posted in Python onDecember 30, 2020

用一条直线对数据进行拟合的过程称为回归。逻辑回归分类的思想是:根据现有数据对分类边界线建立回归公式。
公式表示为:

python编写Logistic逻辑回归

一、梯度上升法

每次迭代所有的数据都参与计算。

for 循环次数:
        训练

代码如下:

import numpy as np
import matplotlib.pyplot as plt
def loadData():
 labelVec = []
 dataMat = []
 with open('testSet.txt') as f:
  for line in f.readlines():
   dataMat.append([1.0,line.strip().split()[0],line.strip().split()[1]])
   labelVec.append(line.strip().split()[2])
 return dataMat,labelVec

def Sigmoid(inX):
 return 1/(1+np.exp(-inX))

def trainLR(dataMat,labelVec):
 dataMatrix = np.mat(dataMat).astype(np.float64)
 lableMatrix = np.mat(labelVec).T.astype(np.float64)
 m,n = dataMatrix.shape
 w = np.ones((n,1))
 alpha = 0.001
 for i in range(500):
  predict = Sigmoid(dataMatrix*w)
  error = predict-lableMatrix
  w = w - alpha*dataMatrix.T*error
 return w


def plotBestFit(wei,data,label):
 if type(wei).__name__ == 'ndarray':
  weights = wei
 else:
  weights = wei.getA()
 fig = plt.figure(0)
 ax = fig.add_subplot(111)
 xxx = np.arange(-3,3,0.1)
 yyy = - weights[0]/weights[2] - weights[1]/weights[2]*xxx
 ax.plot(xxx,yyy)
 cord1 = []
 cord0 = []
 for i in range(len(label)):
  if label[i] == 1:
   cord1.append(data[i][1:3])
  else:
   cord0.append(data[i][1:3])
 cord1 = np.array(cord1)
 cord0 = np.array(cord0)
 ax.scatter(cord1[:,0],cord1[:,1],c='red')
 ax.scatter(cord0[:,0],cord0[:,1],c='green')
 plt.show()

if __name__ == "__main__":
 data,label = loadData()
 data = np.array(data).astype(np.float64)
 label = [int(item) for item in label]
 weight = trainLR(data,label)
 plotBestFit(weight,data,label)

二、随机梯度上升法

1.学习参数随迭代次数调整,可以缓解参数的高频波动。
2.随机选取样本来更新回归参数,可以减少周期性的波动。

python编写Logistic逻辑回归

for 循环次数:
    for 样本数量:
        更新学习速率
        随机选取样本
        训练
        在样本集中删除该样本

代码如下:

import numpy as np
import matplotlib.pyplot as plt
def loadData():
 labelVec = []
 dataMat = []
 with open('testSet.txt') as f:
  for line in f.readlines():
   dataMat.append([1.0,line.strip().split()[0],line.strip().split()[1]])
   labelVec.append(line.strip().split()[2])
 return dataMat,labelVec

def Sigmoid(inX):
 return 1/(1+np.exp(-inX))


def plotBestFit(wei,data,label):
 if type(wei).__name__ == 'ndarray':
  weights = wei
 else:
  weights = wei.getA()
 fig = plt.figure(0)
 ax = fig.add_subplot(111)
 xxx = np.arange(-3,3,0.1)
 yyy = - weights[0]/weights[2] - weights[1]/weights[2]*xxx
 ax.plot(xxx,yyy)
 cord1 = []
 cord0 = []
 for i in range(len(label)):
  if label[i] == 1:
   cord1.append(data[i][1:3])
  else:
   cord0.append(data[i][1:3])
 cord1 = np.array(cord1)
 cord0 = np.array(cord0)
 ax.scatter(cord1[:,0],cord1[:,1],c='red')
 ax.scatter(cord0[:,0],cord0[:,1],c='green')
 plt.show()

def stocGradAscent(dataMat,labelVec,trainLoop):
 m,n = np.shape(dataMat)
 w = np.ones((n,1))
 for j in range(trainLoop):
  dataIndex = range(m)
  for i in range(m):
   alpha = 4/(i+j+1) + 0.01
   randIndex = int(np.random.uniform(0,len(dataIndex)))
   predict = Sigmoid(np.dot(dataMat[dataIndex[randIndex]],w))
   error = predict - labelVec[dataIndex[randIndex]]
   w = w - alpha*error*dataMat[dataIndex[randIndex]].reshape(n,1)
   np.delete(dataIndex,randIndex,0)
 return w

if __name__ == "__main__":
 data,label = loadData()
 data = np.array(data).astype(np.float64)
 label = [int(item) for item in label]
 weight = stocGradAscent(data,label,300) 
 plotBestFit(weight,data,label)

三、编程技巧

1.字符串提取

将字符串中的'\n', ‘\r', ‘\t', ' ‘去除,按空格符划分。

string.strip().split()

2.判断类型

if type(secondTree[value]).__name__ == 'dict':

3.乘法

numpy两个矩阵类型的向量相乘,结果还是一个矩阵

c = a*b

c
Out[66]: matrix([[ 6.830482]])

两个向量类型的向量相乘,结果为一个二维数组

b
Out[80]: 
array([[ 1.],
  [ 1.],
  [ 1.]])

a
Out[81]: array([1, 2, 3])

a*b
Out[82]: 
array([[ 1., 2., 3.],
  [ 1., 2., 3.],
  [ 1., 2., 3.]])

b*a
Out[83]: 
array([[ 1., 2., 3.],
  [ 1., 2., 3.],
  [ 1., 2., 3.]])

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持三水点靠木。

Python 相关文章推荐
Python实现动态添加类的属性或成员函数的解决方法
Jul 16 Python
Python中用函数作为返回值和实现闭包的教程
Apr 27 Python
在Python中使用matplotlib模块绘制数据图的示例
May 04 Python
Python和JavaScript间代码转换的4个工具
Feb 22 Python
python django 增删改查操作 数据库Mysql
Jul 27 Python
python使用原始套接字发送二层包(链路层帧)的方法
Jul 22 Python
Django对models里的objects的使用详解
Aug 17 Python
Jupyter notebook如何实现指定浏览器打开
May 13 Python
Python可以实现栈的结构吗
May 27 Python
python如何更新包
Jun 11 Python
一文解决django 2.2与mysql兼容性问题
Jul 15 Python
如何Tkinter模块编写Python图形界面
Oct 14 Python
python+selenium识别验证码并登录的示例代码
Dec 21 #Python
python实现随机森林random forest的原理及方法
Dec 21 #Python
python编写分类决策树的代码
Dec 21 #Python
Python基于PyGraphics包实现图片截取功能的方法
Dec 21 #Python
用Python写王者荣耀刷金币脚本
Dec 21 #Python
python使用Apriori算法进行关联性解析
Dec 21 #Python
python实现kMeans算法
Dec 21 #Python
You might like
php添加文章时生成静态HTML文章的实现代码
2013/02/17 PHP
详谈PHP文件目录基础操作
2014/11/11 PHP
WebQQ最新登陆协议的用法
2014/12/22 PHP
WordPress中"无法将上传的文件移动至"错误的解决方法
2015/07/01 PHP
PHP实现深度优先搜索算法(DFS,Depth First Search)详解
2017/09/16 PHP
php中pcntl_fork创建子进程的方法实例
2019/03/14 PHP
PHP code 验证码生成类定义和简单使用示例
2020/05/27 PHP
javascript 单例/单体模式(Singleton)
2011/04/07 Javascript
jquery中页面Ajax方法$.load的功能使用介绍
2014/10/20 Javascript
不得不分享的JavaScript常用方法函数集(上)
2015/12/23 Javascript
AngularJS使用自定义指令替代ng-repeat的方法
2016/09/17 Javascript
微信小程序 POST请求(网络请求)详解及实例代码
2016/11/16 Javascript
Vue开发过程中遇到的疑惑知识点总结
2017/01/20 Javascript
Angularjs中的验证input输入框只能输入数字和小数点的写法(推荐)
2017/08/16 Javascript
vue仿淘宝订单状态的tab切换效果
2020/06/23 Javascript
axios简单实现小程序延时loading指示
2018/07/30 Javascript
JavaScript选择排序算法原理与实现方法示例
2018/08/06 Javascript
javascript实现5秒倒计时并跳转功能
2019/06/20 Javascript
[04:00]黄浦江畔,再会英雄——完美世界DOTA2 TI9应援视频
2019/07/31 DOTA
详解Python中的序列化与反序列化的使用
2015/06/30 Python
python http接口自动化脚本详解
2018/01/02 Python
python web框架 django wsgi原理解析
2019/08/20 Python
把vgg-face.mat权重迁移到pytorch模型示例
2019/12/27 Python
python文件和文件夹复制函数
2020/02/07 Python
python matplotlib绘制三维图的示例
2020/09/24 Python
Python数据模型与Python对象模型的相关总结
2021/01/26 Python
萌新的HTML5 入门指南
2020/11/06 HTML / CSS
Casadei卡萨蒂官网:意大利奢侈鞋履品牌
2017/10/28 全球购物
Jones New York官网:美国女装品牌,受白领女性欢迎
2019/11/26 全球购物
高中的职业生涯规划书
2013/12/28 职场文书
经贸韩语专业大学生职业规划
2014/02/14 职场文书
民事诉讼授权委托书范文
2014/08/02 职场文书
2014教师党员自我评议总结
2014/09/19 职场文书
党员带头倡议书
2015/04/29 职场文书
2016年禁毒宣传活动总结
2016/04/05 职场文书
mysql字符串截取函数小结
2021/04/05 MySQL