1. 说明
本系列博客记录B站课程《PyTorch深度学习实践》的实践代码课程链接请点我
2. Pytorch写代码的一般逻辑![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/194b6935f592a335a7f9ed55f4e9e030.png)
3. 代码
# ---------------------------
# @Time : 2022/4/12 18:17
# @Author : lcq
# @File : Logistic_Regression.py
# @Function : PyTorch实现Logistic回归
# ---------------------------
import torch
# x,y是矩阵,3行1列 也就是说总共有3个样本,每个样本只有1个特征
x = torch.tensor([[1.0], [2.0], [3.0]])
y = torch.tensor([[0.0], [0.0], [1.0]])
class LogisticRegressionModel(torch.nn.Module):
def __init__(self):
super(LogisticRegressionModel, self).__init__()
self.linear = torch.nn.Linear(1, 1)
def forward(self, X):
y_pred = torch.sigmoid(self.linear(X))
return y_pred
# Step1: 创建模型
model = LogisticRegressionModel()
# Step2: 创建损失函数和优化器
Loss = torch.nn.BCELoss(size_average=True, reduction=True)
optimizer = torch.optim.SGD(params=model.parameters(), lr=0.01)
# Step3: 训练
for epoch in range(100):
y_pred = model.forward(x)
loss = Loss(y_pred, y)
print(epoch, loss.item())
optimizer.zero_grad()
loss.backward()
optimizer.step()
print('w = ', model.linear.weight.item())
print('b = ', model.linear.bias.item())
x_test = torch.Tensor([[4.0]])
y_test = model(x_test)
print('y_pred = ', y_test.data)