X_data = torch.Tensor([[1.0],[2.0],[3.0]])
Y_data = torch.Tensor([[0],[0],[1]])
#构建模型
class LogisticRegressionModel(torch.nn.Module):
def __init__(self):
super(LogisticRegressionModel,self).__init__() #继承Module的父类
self.linear = torch.nn.Linear(1,1)
def forward(self , x):
y_pred = torch.sigmoid(self.linear(x))
return y_pred
model = LogisticRegressionModel()
#构建损失函数
criterion = torch.nn.BCELoss(reduction='sum')
#构建优化器
optimizer = torch.optim.SGD(model.parameters(),lr = 0.01)
#训练模型
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()
训练结果:
994 1.08380126953125
995 1.0832830667495728
996 1.0827655792236328
997 1.0822484493255615
998 1.0817