본문 바로가기

프로그래머/Pytorch

[pytorch] linear regression class를 nn.Sequential로 간단하게 표현

linear regression class를 nn.Sequential로 간단하게 표현

Linear regression 전체 코드

import torch
import torch.nn.functional as F
import torch.nn as nn
import torch.optim as optim

x_data = [[1,2], [2,3], [3,1], [4,3], [5,3], [6,2]]
y_data = [[0], [0], [0], [1], [1], [1]]
x_train = torch.FloatTensor(x_data)
y_train = torch.FloatTensor(y_data)

print(x_train.size())
print(y_train.size())

'''
class linearRModel(nn.Module):
    def __init__(self):
        super(linearRModel, self).__init__()
        self.linear = nn.Linear(2,1)
        self.sigmoid = nn.Sigmoid()

    def forward(self, x):
        return self.sigmoid(self.linear(x))

model = linearRModel()
'''

model = nn.Sequential(
    nn.Linear(2,1),
    nn.Sigmoid()
)


optimizer = torch.optim.SGD(model.parameters(), lr=1)

for epoch in range(1000):
    hypothesis = model(x_train)
    loss = F.binary_cross_entropy(hypothesis, y_train)
    optimizer.zero_grad()
    loss.backward()
    optimizer.step()

    if epoch % 100 == 0:
        prediction = hypothesis > torch.FloatTensor([0.5])
        correct_prediction = prediction.float() == y_train
        accuracy = correct_prediction.sum().item() / len(correct_prediction)

        print('epoch:{} loss:{:.4f} accuracy:{:2.2f}%'.format(epoch, loss.item(), accuracy*100))
model = nn.Sequential(
    nn.Linear(2,1),
    nn.Sigmoid()
)
class linearRModel(nn.Module):
    def __init__(self):
        super(linearRModel, self).__init__()
        self.linear = nn.Linear(2,1)
        self.sigmoid = nn.Sigmoid()

    def forward(self, x):
        return self.sigmoid(self.linear(x))

model = linearRModel()

위 두개는 동치이다.