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()
위 두개는 동치이다.
'프로그래머 > Pytorch' 카테고리의 다른 글
[Pytorch] RNN으로 문장 학습시키기 (0) | 2020.06.23 |
---|---|
ants/bees classification CNN model에서 배울 수 있는 소소한 팁들(python) (0) | 2020.06.22 |
[Pytorch] 기초 강의 day1 (0) | 2020.06.15 |
[Pytorch] VGG CIFAR-10에 적용 및 정리 (2) | 2020.06.07 |
[Pytorch] VGG 구현 및 정리 (2) | 2020.06.07 |