이번 강의에서는 Multivariable Linear regression에 대하여 정리해보도록 하겠습니다.
지금까지는 하나의 인자에 대해서만 예측을 진행하였는데
정보가 많은 경우 어떻게 예측을 진행하는지 알아보도록 하겠습니다.
학습 목표
다항 선형 회귀(Multivariable Linear regression)에 대해 알아본다.
핵심 키워드
다항 선형 회귀(Multivariable Linear regression)
가설 함수(Hypothesis Function)
평균 제곱 오차(Mean Squared Error)
경사 하강법(Gradient descent)
1. 다항 선형 회귀(Multivariable Linear regression)
다항 선형 회귀는 증가한 인자의 개수만큼 W를 추가하여 각각의 x에 더해주면 된다. 이제 다항 선형 회귀를 이용한 간단한 실습을 진행해보자!! 실습은 총 두 가지의 방법으로 진행하겠습니다. 첫 번째 방법은 단지 수학적 수식을 이용하는 방법, 두 번째 방법은 PyTorch에서 제공하는 nn.Model을 사용하는 방법으로 진행하겠습니다.
2. 다항 선형 회귀 실습
Quize 1 | Quize 2 | Quize 3 | Final |
73 | 80 | 75 | 152 |
93 | 88 | 93 | 185 |
89 | 91 | 80 | 180 |
96 | 98 | 100 | 196 |
73 | 66 | 70 | 142 |
1) 수식을 이용한 실습
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
# 데이터
x1_train = torch.FloatTensor([[73], [93], [89], [96], [73]])
x2_train = torch.FloatTensor([[80], [88], [91], [98], [66]])
x3_train = torch.FloatTensor([[75], [93], [90], [100], [70]])
y_train = torch.FloatTensor([[152], [185], [180], [196], [142]])
먼저 위의 표에 맞게 학습 데이터를 준비합니다.
# 모델 초기화
w1 = torch.zeros(1, requires_grad=True)
w2 = torch.zeros(1, requires_grad=True)
w3 = torch.zeros(1, requires_grad=True)
b = torch.zeros(1, requires_grad=True)
# Optimizer 설정
optimizer = optim.SGD([w1, w2, w3, b], lr=1e-5)
nb_epochs = 1000
for epoch in range(nb_epochs + 1):
# H(x) 계산
hypothesis = w1*x1_train + w2*x2_train + w3*x3_train + b
# cost 계산
cost = torch.mean((hypothesis - y_train)**2)
#cost로 H(x) 개선
optimizer.zero_grad() # gradient를 0으로 초기화
cost.backward() # gradient 계산
optimizer.step() # lr만큼 step 이동
# 100번마다 로그 출력
if epoch % 100 == 0:
print('Epoch {:4d}/{} w1: {:.3f} w2: {:.3f} w3: {:.3f} b: {:.3f} Cost: {:.6f}'.format(
epoch, nb_epochs, w1.item(), w3.item(), w3.item(), b.item(), cost.item()
))
단항 선형 회귀와 비교해 보았을 때 W의 개수와 X의 개수가 증가하여 H(x)를 조금 다르게 정의한 것을 제외하고는 크게 차이가 없다. 그러나 여기서 주목해야될 점이 현재 예제에서는 x가 3개이기 때문에 일일이 하나씩 곱하여 더하고 표현해 줄 수 있었지만 x의 개수가 100개, 1000개로 늘어나면 이렇게 정의하는 것은 실질적으로 불가능할 것이다. 따라서 이를 조금 더 실용적으로 표현할 수 있도록 다음과 같이 행렬의 연산을 이용할 수 있다.
행렬의 연산을 사용하면 H(x)를 다음과 같이 정의할 수 있습니다.
# dot product를 사용한 H(x)
hypothesis = x_train.matmul(W) + b
이제 PyTorch의 다양한 모듈을 활용하여 똑같은 실습을 다시 진행해보도록 하겠다.
2) nn.Modules 이용한 실습
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
# 모델 정의
class MultivariateLinearRegressionModel(nn.Module):
def __init__(self):
super.__init__()
self.linear = nn.Linear(3,1) # input_dim=3, output_dim=1
def forward(self, x):
return self.linear(x)
다음과 같이 모델을 정의할 수 있다. 세개의 x에 대하여 한 개의 y가 출력되므로 3,1을 인자로 주었다.
# 데이터
x_train = torch.FloatTensor([[73, 80, 75],
[93, 88, 93],
[89, 91, 90],
[96, 98, 100],
[73, 66, 70]])
y_train = torch.FloatTensor([[152], [185], [180], [196], [142]])
model = MultivariateLinearRegressionModel()
# optimizer 설정
optimizer = optim.SGD(model.parameters(), lr=1e-5)
nb_epochs = 1000
for epoch in range(nb_epochs + 1):
# H(x) 계산
prediction = model(x_train)
# cost 계산
cost = F.mse_loss(prediction, y_train)
# 100번마다 로그 출력
if epoch % 100 == 0:
print('Epoch {:4d}/{} Cost: {:.6f}'.format(
epoch, nb_epochs, cost.item()
))
지금까지 다항 선형회귀에 대하여 학습하고
수식을 사용한 방법, 다양한 모듈을 사용한 방법 두 가지 모두 실습을 진행해보았다.
우리가 지금까지 실습해본 예제들은 모두 단순한 데이터에 대한 예측이었다.
하지만 실생활에서는 이것보다 훨씬 크고 많은 데이터를 처리하게 될 것이다.
다음 강의에서는 이렇게 큰 데이터에 대해서는 어떻게 처리해야 되는지
배워보도록 하겠습니다!!!
'모두를 위한 딥런닝 by PyTorch' 카테고리의 다른 글
Lab-06 Softmax Classification (0) | 2021.08.14 |
---|---|
Lab-05 Logistic Regression (0) | 2021.08.12 |
Lab-04-2 Minibatch Gradient Descent (0) | 2021.08.09 |
Lab-02,03 Linear Regression (0) | 2021.08.07 |
Lab-01 Tensor Manipulation (0) | 2021.08.07 |