1.PyTorch基础实现Logistic regression
import torch
from torch.autograd import Variable
torch.manual_seed(2)
x_data = Variable(torch.Tensor([[1.0], [2.0], [3.0], [4.0]]))
y_data = Variable(torch.Tensor([[0.0], [0.0], [1.0], [1.0]]))
w = Variable(torch.Tensor([-1]), requires_grad=True)
b = Variable(torch.Tensor([0]), requires_grad=True)
epochs = 100
costs = []
lr = 0.1
print('before training,predict of x = 1.5 is :')
print('Y_pred = ', float(w.data * 1.5 + b.data > 0))
for epoch in range(epochs):
A = 1 / (1 + torch.exp(-(w * x_data + b)))
J = - torch.mean(y_data * torch.log(A) + (1 - y_data) * torch.log(1 - A))
J.backward()
w.data = w.data - lr * w.grad.data
w.grad.data.zero_()
b.data = b.data - lr * b.grad.data
b.grad.data.zero_()
print('after trainning,predict of x = 1.5 is :')
print('Y_pred = ', float(w.data * 1.5 + b.data > 0))
print(w.data, b.data)
2. 用PyTorch类实现Logistic regression,torch.nn.module写网络结构
import torch
from torch.autograd import Variable
torch.manual_seed(2)
x_data = Variable(torch.Tensor([[1.0], [2.0], [3.0], [4.0]]))
y_data = Variable(torch.Tensor([[0.0], [0.0], [1.0], [1.0]]))
class Model(torch.nn.Module):
def __init__(self):
super(Model, self).__init__()
self.linear = torch.nn.Linear(1, 1)
def forward(self, x):
y_pred = self.linear(x)
return y_pred
model = Model()
criterion = torch.nn.BCEWithLogitsLoss()
optimizer = torch.optim.SGD(model.parameters(), lr=0.01)
hour_var = Variable(torch.Tensor([[2.5]]))
y_pred = model(hour_var)
print("predict (before training) given", 4, "is", float(model(hour_var).data[0][0] > 0.5))
epochs = 40
for epoch in range(epochs):
y_pred = model(x_data)
loss = criterion(y_pred, y_data)
optimizer.zero_grad()
loss.backward()
optimizer.step()
hour_var = Variable(torch.Tensor([[4.0]]))
y_pred = model(hour_var)
print("predict (after training) given", 4, "is", float(model(hour_var).data[0][0] > 0.5))