Notice
Recent Posts
Recent Comments
Link
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | 4 | |||
5 | 6 | 7 | 8 | 9 | 10 | 11 |
12 | 13 | 14 | 15 | 16 | 17 | 18 |
19 | 20 | 21 | 22 | 23 | 24 | 25 |
26 | 27 | 28 | 29 | 30 | 31 |
Tags
- pytorch
- 리눅스
- 딥러닝
- NERF
- Deep Learning
- IROS
- panoptic segmentation
- CVPR
- ICCV 2021
- GAN
- 논문리뷰
- 논문
- Neural Radiance Field
- paper review
- Python
- panoptic nerf
- 2022
- CVPR2023
- Paper
- ICCV
- docker
- 경희대
- 논문 리뷰
- 파이토치
- Computer Vision
- linux
- 융합연구
- Semantic Segmentation
- NeRF paper
- Vae
Archives
- Today
- Total
윤제로의 제로베이스
클래스로 로지스틱 회귀 모델 구현하기 본문
1. 모델을 클래스로 구현하기
model = nn.Sequential(
nn.Linear(2, 1), # input_dim = 2, output_dim = 1
nn.Sigmoid() # 출력은 시그모이드 함수를 거친다
)
class BinaryClassifier(nn.Module):
def __init__(self):
super().__init__()
self.linear = nn.Linear(2, 1)
self.sigmoid = nn.Sigmoid()
def forward(self, x):
return self.sigmoid(self.linear(x))
nn.Module을 상속받는다.
그리고 __init__()에서 모델의 구조와 동적을 정의한느 생성자를 정의한다.
객체가 갖는 속성값을 초기화하는 역할로, 객체가 생성될 때 자동으로 호출된다.
super()함수를 부르면 여기서 만든 클래스는 nn.Module 클래스의 속성들을 가지고 초기화 된다.
forward() 함수는 모델이 학습 데이터를 입력 받아 forward연산을 진행시키는 함수이다.
이 forward() 함수는 model. 객체를 데이터와 함께 호출하면 자동으로 실행된다.
2. 로지스틱 회귀 클래스로 구현하기
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
torch.manual_seed(1)
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)
class BinaryClassifier(nn.Module):
def __init__(self):
super().__init__()
self.linear = nn.Linear(2, 1)
self.sigmoid = nn.Sigmoid()
def forward(self, x):
return self.sigmoid(self.linear(x))
model = BinaryClassifier()
# optimizer 설정
optimizer = optim.SGD(model.parameters(), lr=1)
nb_epochs = 1000
for epoch in range(nb_epochs + 1):
# H(x) 계산
hypothesis = model(x_train)
# cost 계산
cost = F.binary_cross_entropy(hypothesis, y_train)
# cost로 H(x) 개선
optimizer.zero_grad()
cost.backward()
optimizer.step()
# 20번마다 로그 출력
if epoch % 10 == 0:
prediction = hypothesis >= torch.FloatTensor([0.5]) # 예측값이 0.5를 넘으면 True로 간주
correct_prediction = prediction.float() == y_train # 실제값과 일치하는 경우만 True로 간주
accuracy = correct_prediction.sum().item() / len(correct_prediction) # 정확도를 계산
print('Epoch {:4d}/{} Cost: {:.6f} Accuracy {:2.2f}%'.format( # 각 에포크마다 정확도를 출력
epoch, nb_epochs, cost.item(), accuracy * 100,
))
'Background > Pytorch 기초' 카테고리의 다른 글
소프트맥스 회귀(Softmax Regression) 이해하기 (0) | 2022.01.16 |
---|---|
원-핫 인코딩 (One-Hot Encoding) (0) | 2022.01.16 |
nn.Module로 구현하는 로지스틱 회귀 (0) | 2022.01.16 |
로지스틱 회귀 (Logistic Regression) (0) | 2022.01.16 |
커스텀 데이터셋 (Custom Dataset) (0) | 2022.01.16 |