PyTorch实现Logistic regression
import torch
from torch.autograd import Variable
x_data = Variable(torch.Tensor([[0.2], [.5], [3.5], [4.5]]))
y_data = Variable(torch.Tensor([[0.], [0.], [1.], [1.]]))
class MyModel(torch.nn.Module):
def __init__(self):
super(Model, self).__init__()
self.input = torch.nn.Linear(1, 1)
self.output = torch.nn.Sigmoid()
def forward(self, x):
y = self.output(self.input(x))
return y
myModel = MyModel()
loss = torch.nn.BCELoss(size_average=True)
opt = torch.optim.SGD(myModel.parameters(), lr=0.01)
for epoch in range(500):
# Forward pass
y_pred = myModel(x_data)
loss = loss(y_pred, y_data)
if epoch % 10 == 0:
print(epoch, loss.item())
opt.zero_grad()
loss.backward()
opt.step()