1,代码如下
import imp
from statistics import mode
import torch.nn.functional as F
import torch
# 1, Prepare data
x_data = torch.Tensor([[1.0],[2.0],[3.0]])
y_data = torch.Tensor([[0],[0],[1]])
# 2, Design model
class LogisticRegressionModel(torch.nn.Module):
def __init__(self) -> None: # 初始化函数
super(LogisticRegressionModel,self).__init__()
self.linear = torch.nn.Linear(1,1)
def forward(self,x): # 前馈计算
y_pred = F.sigmoid(self.linear(x))
return y_pred
model = LogisticRegressionModel()
# 3, Select criterion and optimizer (using PyTorch API)
criterion = torch.nn.BCELoss(size_average=False)
optimizer = torch.optim.SGD(model.parameters(),lr=0.01) # 优化器(梯度下降)
# 4, Training cycle
for epoch in range(1000):
y_pred = model(x_data)
loss = criterion(y_pred,y_data)
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)