python编写Logistic逻辑回归
作者:开贰锤 时间:2022-03-04 16:57:03
用一条直线对数据进行拟合的过程称为回归。逻辑回归分类的思想是:根据现有数据对分类边界线建立回归公式。
公式表示为:
一、梯度上升法
每次迭代所有的数据都参与计算。
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
标签:python,Logistic,逻辑回归
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
Data URI 和 MHTML
2009-08-16 16:19:00
PDO::commit讲解
2023-06-14 05:35:45
django 基于中间件实现限制ip频繁访问过程详解
2022-06-24 08:38:43
ASP FSO生成静态htm页面简单代码
2010-04-24 16:04:00
详解php中curl返回false的解决办法
2023-10-01 05:53:22
python如何读取和存储dict()与.json格式文件
2021-12-07 16:13:36
![](https://img.aspxhome.com/file/2023/6/90326_0s.png)
WEB2.0网页制作标准教程(2)什么是名字空间
2007-11-13 13:04:00
wxPython定时器wx.Timer简单应用实例
2022-08-20 00:36:30
![](https://img.aspxhome.com/file/2023/9/83979_0s.jpg)
详解pyenv下使用python matplotlib模块的问题解决
2023-08-08 20:25:01
![](https://img.aspxhome.com/file/2023/6/104946_0s.png)
Python中and和or如何使用
2022-04-27 18:01:49
解析Mac OS下部署Pyhton的Django框架项目的过程
2021-04-03 14:00:34
python matplotlib画图实例代码分享
2022-06-12 23:12:21
![](https://img.aspxhome.com/file/2023/5/117865_0s.png)
django使用haystack调用Elasticsearch实现索引搜索
2021-07-22 17:13:27
![](https://img.aspxhome.com/file/2023/2/113152_0s.png)
python利用Excel读取和存储测试数据完成接口自动化教程
2022-04-02 05:25:13
![](https://img.aspxhome.com/file/2023/4/75324_0s.jpg)
详解pytorch 0.4.0迁移指南
2023-04-10 08:02:14
![](https://img.aspxhome.com/file/2023/0/84920_0s.jpg)
浅谈Python函数式编程的返回函数与匿名函数
2021-02-22 13:40:36
python编写脚本之pyautogui的安装和使用教程
2021-06-17 09:48:11
![](https://img.aspxhome.com/file/2023/8/92498_0s.png)
解决MySQL启动时1067错误
2010-09-30 14:09:00
Python对Excel按列值筛选并拆分表格到多个文件的代码
2022-01-18 12:58:46
Python+Opencv实战之人脸追踪详解
2022-09-22 16:03:38
![](https://img.aspxhome.com/file/2023/6/99136_0s.gif)