pytorch实现逻辑回归
一 、逻辑回归简单介绍
逻辑回归虽然叫做回归,但是其主要解决分类问题。可用于二分类,也可以用于多分类问题。
由于线性回归其预测值为连续变量,其预测值在整个实数域中。而对于预测变量y为离散值(如0,1等)时候,可以用逻辑回归算法(Logistic Regression)
1.1 逻辑回归原理
逻辑回归模型的假设是:
其中,g代表逻辑函数,逻辑函数在逻辑回归中为sigmoid函数,简称S型函数。
详细介绍见 https://blog.csdn.net/wehung/article/details/88930535#2__13
1.2 损失函数
二、代码实现
2.1 导入相关库
# Load Library
import numpy as np
import torch
2.2 导入数据
torch.manual_seed(42)
x_data = torch.Tensor([[1.0],[2.0],[3.0],[4.0]]) #或者 torch.Tensor(np.array([[1.0],[2.0],[3.0],[4.0]]))
y_data = torch.Tensor([[0.0],[0.0],[1.0],[1.0]])
print(x_data.shape)
print(y_data.shape)
out:
torch.Size([4, 1])
torch.Size([4, 1])
sigmoid函数
1./(1+torch.exp(w*x_data))
三 方法1:直接使用logistic regression(逻辑回归)定义+pytorch梯度计算
3.1 初始化
w = torch.tensor([[0.0]], requires_grad=True)
b = torch.tensor([[0.0]], requires_grad=True)
print(w.shape)
print(b.shape)
epoches =1000 #
costs = [] #代价
lr =0.1 #学习率
out:
torch.Size([1, 1])
torch.Size([1, 1])
len(x_data)#数据集数目
pred = sigmoid(w,x_data,b) #逻辑回归定义sigmod函数
pred
out:
tensor([[0.5000],
[0.5000],
[0.5000],
[0.5000]], grad_fn=<MulBackward0>)
训练前:
print("befor training,predicion of x =1.5 is:")
print(w.data*1.5+b.data)
print("Y_pred",float((w.data*1.5+b.data)>0))
out:
befor training,predicion of x =1.5 is:
tensor([[0.]])
Y_pred 0.0
3.2 训练
for epoch in range(epoches):
pred=1./(1+torch.exp(-(w*x_data+b))) #逻辑回归函数
J = -1./len(x_data) *sum(y_data*torch.log(pred)+(1-y_data)*torch.log(1-pred)) #损失函数
#J = torch.mean(y_data*torch.log(A)+(1-y_data)*torch.log(1-A))
# J = - 1./len(x_data) *sum((y_data*torch.log(pred)+(1-y_data)*torchlog(1-pred)))+alpha*W**2 正则化表达式
costs.append(J.item())#因为为实数 可以直接tensor.item()
J.backward()
#参数更新
w.data = w.data - lr*w.grad.data
w.grad.data.zero_()
b.data = b.data -lr*b.grad.data
b.grad.data.zero_()
训练后
print("after training,predicion of x =1.5 is:")
print(w.data*1.5+b.data)
print("Y_pred",float((w.data*1.5+b.data)>0))
out:
after training,predicion of x =1.5 is:
tensor([[-2.1164]])
Y_pred 0.0
此时的w
print(w)
out:
tensor([[2.3867]], requires_grad=True)
**训练次数及代价示意图**
#损失函数图
import matplotlib.pyplot as plt
%matplotlib inline
fig, ax = plt.subplots(figsize=(12,8))
ax.plot(np.arange(epoches), costs, 'r')
ax.set_xlabel('Iterations')
ax.set_ylabel('Cost')
ax.set_title('Error vs. Training Epoch 训练次数 损失函数图')
plt.show()
4 方法2:使用神经网络方法
由于我们的数据是输入是1 维 输出也是1维 故可以尝试使用线性函数训练。
4.1 导入相关库
#导入相关库
import torch
import torch.nn as nn
4.2 定义模型
创建类
class Model(nn.Module):
def __init__(self):
super(Model,self).__init__() #继承 nn.Module
self.linear = nn.Linear(1,1) #输入为1 输出为1
def forward(self,x):
y_pred = self.linear(x) #前向反馈
return y_pred
模型实例化
model = Model()
定义损失函数以及优化方法
#定义损失函数方法以及优化方法
criterion = nn.BCEWithLogitsLoss()#nn中封装好的损失函数
optimizer = torch.optim.SGD(model.parameters(),lr=0.01) #随机梯度下降
hour_var = torch.tensor([[2.5]])
y_pr = model(hour_var)
#print("before Model traing",2.5 ," is ")
print(y_pr)
print(y_pr.data[0][0]>0.5)
out:
tensor([[4.6914]], grad_fn=<AddmmBackward>)
tensor(1, dtype=torch.uint8)
4.3 训练
epoches = 40
for epoch in range(epoches):
y_pred = model(x_data)
loss = criterion(y_data,y_pred)
#print("epoch = ", epoch+1, " loss=",loss.item())
optimizer.zero_grad() #梯度清零
loss.backward()
optimizer.step()
list(model.parameters())
out:
[Parameter containing:
tensor([[1.4645]], requires_grad=True), Parameter containing:
tensor([1.0300], requires_grad=True)]
print("after Model traing",2.5 ," is ")
print(y_pred.data[0][0]>0.5)
out:
after Model traing 2.5 is
tensor(1, dtype=torch.uint8)