크크루쿠쿠

DL04. Linear Regression in the PyTorch way 본문

DeepLearning/공부

DL04. Linear Regression in the PyTorch way

JH_KIM 2021. 1. 13. 00:31

 

PyTorch forward/backward pass

 

 

  • Forward pass. →

값을 대입함으로써 loss를 계산하는 과정

  • Backward pass ←

계산된 loss를 이용하여 뒷 방향으로 gradient값 chain rule이용해 넘겨줌

 

 

PyTorch Rhythm

 

1. model을 class와 Variables를 사용해서 디자인 해라

 

torch model에서 필요한 두가지

  1. __ init __
  1. forward

init 함수는 말그대로 생성자 느낌.

여기 예시에서는 한개의 input 이 들어가 한개의 output이 나오므로 torch.nn.Linear(1,1)로 해줌

 

forward는 x라는 input을 model에 넣었을 때 예상값

2. loss함수와 optimizer 결정

 

전에 배웠던 MSE loss function을 사용하기 위해 torch.nn.MSELoss() 로 함수 설정

optimizer는 loss가 적어지게끔 찾아가는 방법? 이라 생각하면 된다.

 

3. Training cycle

 

 

학습해주는 과정.

 

 

Code

 

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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
from torch import nn
import torch
from torch import tensor
 
x_data = tensor([[1.0], [2.0], [3.0]])
y_data = tensor([[2.0], [4.0], [6.0]])
 
 
class Model(nn.Module):
    def __init__(self):
        """
        In the constructor we instantiate two nn.Linear module
        """
        super(Model, self).__init__()
        self.linear = torch.nn.Linear(11)  # One in and one out
 
    def forward(self, x):
        """
        In the forward function we accept a Variable of input data and we must return
        a Variable of output data. We can use Modules defined in the constructor as
        well as arbitrary operators on Variables.
        """
        y_pred = self.linear(x)
        return y_pred
 
 
# our model
model = Model()
 
# Construct our loss function and an Optimizer. The call to model.parameters()
# in the SGD constructor will contain the learnable parameters of the two
# nn.Linear modules which are members of the model.
criterion = torch.nn.MSELoss(reduction='sum')
optimizer = torch.optim.SGD(model.parameters(), lr=0.01)
 
# Training loop
for epoch in range(500):
    # 1) Forward pass: x_data를 input값으로 model에 넣어줌
    y_pred = model(x_data)
 
    # 2) loss 계산해서 출력
    loss = criterion(y_pred, y_data)
    print(f'Epoch: {epoch} | Loss: {loss.item()} ')
 
    # Zero gradients, perform a backward pass, and update the weights.
    optimizer.zero_grad() #gradient들 초기화
    loss.backward() #자동으로 backward pass 해줌
    optimizer.step() # gradient 결과들로 variable들 바꿔줌
 
 
# After training
hour_var = tensor([[4.0]])
y_pred = model(hour_var)
print("Prediction (after training)",  4, model(hour_var).data[0][0].item())
cs

'DeepLearning > 공부' 카테고리의 다른 글

Prompt Engineering Guide 1. Introduction  (0) 2023.03.27
NLP 01.Text Classification  (0) 2021.01.21
DL03. Back-propagation 역전파  (0) 2021.01.09
DL02. Gradient Descent  (0) 2021.01.06
DL01.Linear Model  (0) 2021.01.06
Comments