python编写Logistic逻辑回归
作者:开贰锤 发布时间:2022-03-04 16:57:03
标签: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.]])
来源:http://blog.csdn.net/weixin_37895339/article/details/78441688
0
投稿
猜你喜欢
- 前言:在转换操作中,我们执行各种操作,例如更改系列的数据类型,将系列更改为列表等。为了执行转换操作,我们有各种有助于转换的功能,例如.ast
- 以下为引用的内容: <html> <head> <title>不刷新页面查询的方法&
- 一、Python下载1.进入Python官网:https://www.python.org/2.选择windows版本(Download &
- Pytorch凭借动态图机制,获得了广泛的使用,大有超越tensorflow的趋势,不过在工程应用上,TF仍然占据优势。有的时候我们会遇到这
- 协同过滤在 用户 —— 物品(user - item)的数据关系下很容易收集到一些偏好信息(preference),比如评分。利用这些分散的
- 由于学习需要安装matplotlib库,阅读网上教程后一直出现各种各样的错误,以下为我的经验总结:声明:本人python版本为3.8.0,p
- 很多人说设计是力求细节的,在网页设计里表达出的细节就是图标。图标在一个设计里带来了额外的注解并且使设计里的对象和元素引起用户的注意。以下介绍
- 本文主要介绍的是MySQL慢查询分析方法,前一段日子,我曾经设置了一次记录在MySQL数据库中对慢于1秒钟的SQL语句进行查询。想起来有几个
- 在使用Ajax过程中,有时候总会遇到一些难题,浏览器兼容、编码、IE下的特殊处理等等,偶尔会搞的人头昏脑胀哭笑不得,这里列一些小贴士,或许有
- key_buffer_size - 这对MyISAM表来说非常重要。如果只是使用MyISAM表,可以把它设置为可用内存的 30-40%。合理
- 由于可将 Microsoft? SQL Server? 2000 设置为包含一个或多个命名实例和一个默认实例(也可无),所以要用新命名规则来
- 引言在观察OpenCV中某个函数在不同参数的情况下,所得到的效果的时候,我之前是改一次参数运行一次,这样做起来操作麻烦,效率低下。为了更便捷
- Python Socket模块中包含一些有用IP转换函数,说明如下:socket.ntohl(x) // 类似于
- 官网资料:loc :https://pandas.pydata.org/pandas-docs/stable/reference
- 本文实例为大家分享了python实现FTP文件下载功能的具体代码,供大家参考,具体内容如下代码:#-*-coding:utf-8-*- im
- 之前介绍过python开发工具Jupyter的使用,今天继续讲解python的数据类型,python中有整型、浮点型、字符串、布尔类型,我们
- 这篇文章主要介绍了python中的Elasticsearch操作汇总,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习
- 一、数据描述数据集中9994条数据,横跨1237天,销售额为2,297,200.8603美元,利润为286,397.0217美元,他们的库存
- 本文实例讲述了Golang最大递减数算法问题。分享给大家供大家参考,具体如下:给出一个非负整数,找到这个非负整数中包含的最大递减数。一个数字
- 在使用Python多年以后,我偶然发现了一些我们过去不知道的功能和特性。一些可以说是非常有用,但却没有充分利用。考虑到这一点,我编辑了一些你