6-逻辑斯蒂回归
注意torch.Tensor()和torch.tensor()的区别
点击查看代码
import torch
import torch.nn.functional as F
x_data = torch.Tensor([[1.0], [2.0], [3.0]])
y_data = torch.Tensor([[0], [0], [1]]) # 注意torch.tensor()和torch.Tensor()的区别
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 = F.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(100):
y_pred = model(x_data)
loss = criterion(y_pred, y_data)
print('epoch=',epoch, 'loss=',loss)
optimizer.zero_grad()
loss.backward()
optimizer.step()