본문 바로가기
모두의 딥러닝/강의자료 정리

Lab_04-1: Multivariable Linear regression

by cvlab_김준수 2025. 1. 15.

이전에는 x가 하나인 선형회귀를 코드로 작성해보았다. 이번에서는 아래와 같이 여러 개의 데이터 x에 따라 예측을 하는 모델을 만들어보자.

 

 

 

 Hypothesis Fuction을 작성해보면 아래와 같이 작성할 수 있다.

 

H(x) = w₁x₁ + w₂x₂ + w₃x₃

 

위 식처럼 작성하면 x가 늘어남에 따라 식도 길어진다. 따라서, x를 행렬로 바꿔서 한번에 계산하면 더 간결하고 속도도 빠른 코드를 작성할 수 있다. matmul을 사용하면 여러개의 벡터를 하나의 행렬로 만들 수 있다.

 

# H(x) 계산 - 벡터
hypothesis = x1_train * w1 + x2_train * w2 + x3_train * w3 + b

# H(x) 계산 - 행렬
hypothesis = x_train.matmul(W) + b

 

 

 

 

파이토치에서 제공하는 모듈 이용하기

import torch.nn.functional as F

 

: Loss  함수를 제공한다. 이후 Loss 함수를 변경할 떄 용이하다.

 

 

import torch.nn as nn

 

: 파라미터 관리 및 모델의 재사용 가능

 

 

 

이렇게 모듈을 이용하면, 아래와 같이 간단하게 모델을 학습시킬 수 있다.

 

import torch
import torch.optim as optim # 쉬운 Gradient 계산
import torch.nn.functional as F # loss 함수 제공 -> loss 함수 변경에 용이
import torch.nn as nn # 파라미터 관리와 모듈의 재사용성을 통해 효율적이고 유지보수가 용이

class MultivariateLinearRegressionModel(nn.Module):
  def __init__(self):
    super().__init__()
    self.linear = nn.Linear(3, 1) # 입력 차원 3, 출력 차원 1
  def forward(self, x): # Hyepothersis 계산
    return self.linear(x)


# (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]])


# (2) 모델 초기화 및 정의
model = MultivariateLinearRegressionModel()


# (3) optimizer 설정
optimizer = optim.SGD(model.parameters(), lr=1e-5)


nb_epochs = 20
for epoch in range(nb_epochs + 1):


  #(4) Hypothesis 계산
  Hypothesis = model(x_train)


  #(5) Cost 계산(MSE)
  cost = F.mse_loss(Hypothesis, y_train)


  #(6) Gradient descent
  optimizer.zero_grad()
  cost.backward()
  optimizer.step()
  
  print('Epoch {:4d}/{} Hypothesis: {} Cost: {:.6f}'.format(
  epoch, nb_epochs, Hypothesis.squeeze().detach(),
  cost.item()
  ))

'모두의 딥러닝 > 강의자료 정리' 카테고리의 다른 글

Lab_05: Logistic Regression  (1) 2025.01.16
Lab_04-2: Loading Data(mini batch)  (0) 2025.01.15
Lab_03: Deeper Look at Gradient Descent  (1) 2025.01.15
Lab_02: Linear regression  (0) 2025.01.06
Lab_01: Tensor Manipulation  (1) 2025.01.05