Path: blob/master/lab-02_linear_regression.ipynb
502 views
Lab 2: Linear Regression
Author: Seungjae Lee (이승재)
nn.Module or nn.Linear are used.
Theoretical Overview
: 주어진 값에 대해 예측을 어떻게 할 것인가
: 가 를 얼마나 잘 예측했는가
Imports
Data
We will use fake data for this example.
기본적으로 PyTorch는 NCHW 형태이다.
Weight Initialization
Hypothesis
Cost
Gradient Descent
Let's check if the hypothesis is now better.
Training with Full Code
In reality, we will be training on the dataset for multiple epochs. This can be done simply with loops.
High-level Implementation with nn.Module
Remember that we had this fake data.
이제 linear regression 모델을 만들면 되는데, 기본적으로 PyTorch의 모든 모델은 제공되는 nn.Module을 inherit 해서 만들게 됩니다.
모델의 __init__에서는 사용할 레이어들을 정의하게 됩니다. 여기서 우리는 linear regression 모델을 만들기 때문에, nn.Linear 를 이용할 것입니다. 그리고 forward에서는 이 모델이 어떻게 입력값에서 출력값을 계산하는지 알려줍니다.
Hypothesis
이제 모델을 생성해서 예측값 를 구해보자
Cost
이제 mean squared error (MSE) 로 cost를 구해보자. MSE 역시 PyTorch에서 기본적으로 제공한다.
Gradient Descent
마지막 주어진 cost를 이용해 의 를 바꾸어서 cost를 줄여봅니다. 이때 PyTorch의 torch.optim 에 있는 optimizer 들 중 하나를 사용할 수 있습니다.
Training with Full Code
이제 Linear Regression 코드를 이해했으니, 실제로 코드를 돌려 피팅시켜보겠습니다.
점점 의 와 를 조정해서 cost가 줄어드는 것을 볼 수 있습니다.