python编写Logistic逻辑回归

 更新时间:2020年12月30日 10:04:34   作者:开贰锤  
这篇文章主要介绍了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.随机选取样本来更新回归参数,可以减少周期性的波动。

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中sorted()排序与字母大小写的问题

    Python中sorted()排序与字母大小写的问题

    这篇文章主要介绍了Python中sorted()排序与字母大小写的问题,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2020-01-01
  • python+matplotlib实现鼠标移动三角形高亮及索引显示

    python+matplotlib实现鼠标移动三角形高亮及索引显示

    这篇文章主要介绍了Python+matplotlib实现鼠标移动三角形高亮及索引显示,具有一定借鉴价值,需要的朋友可以参考下
    2018-01-01
  • python 叠加等边三角形的绘制的实现

    python 叠加等边三角形的绘制的实现

    这篇文章主要介绍了python 叠加等边三角形的绘制的实现,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2019-08-08
  • Python中dict和set的用法讲解

    Python中dict和set的用法讲解

    今天小编就为大家分享一篇关于Python中dict和set的用法讲解,小编觉得内容挺不错的,现在分享给大家,具有很好的参考价值,需要的朋友一起跟随小编来看看吧
    2019-03-03
  • python elasticsearch从创建索引到写入数据的全过程

    python elasticsearch从创建索引到写入数据的全过程

    这篇文章主要介绍了python elasticsearch从创建索引到写入数据的方法,本文通过实例代码给大家介绍的非常详细,具有一定的参考借鉴价值,需要的朋友可以参考下
    2019-08-08
  • Python入门教程(四)Python注释介绍

    Python入门教程(四)Python注释介绍

    这篇文章主要介绍了Python入门教程(四)Python注释介绍,Python是一门非常强大好用的语言,也有着易上手的特性,本文为入门教程,需要的朋友可以参考下
    2023-04-04
  • Python正则表达式使用经典实例

    Python正则表达式使用经典实例

    本文给大家总结了17种python正则表达式使用经典实例,非常不错具有参考借鉴价值,感兴趣的朋友一起学习吧
    2016-06-06
  • python求一个字符串的所有排列的实现方法

    python求一个字符串的所有排列的实现方法

    这篇文章主要介绍了python求一个字符串的所有排列的实现方法,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2020-02-02
  • Python学习笔记之装饰器

    Python学习笔记之装饰器

    这篇文章主要介绍了Python 装饰器的相关资料,文中讲解非常细致,代码帮助大家更好的理解和学习,感兴趣的朋友可以了解下
    2020-08-08
  • JSON文件及Python对JSON文件的读写操作

    JSON文件及Python对JSON文件的读写操作

    JSON和XML都是互联网上数据交换的主要载体。这篇文章主要介绍了JSON文件及Python对JSON文件的读写操作,需要的朋友可以参考下
    2018-10-10

最新评论