now is better than never

[인공지능(AI) 기초 다지기] 5. 딥러닝 핵심 기초 (5) 본문

Python/[코칭스터디 9기] 인공지능 AI 기초 다지기

[인공지능(AI) 기초 다지기] 5. 딥러닝 핵심 기초 (5)

김초송 2023. 3. 7. 17:59

4-1) Multivariable Linear Regression (다항 선형 회귀)

 

- Mulivariable Linear Regression

  • 여러 개의 정보로부터 하나의 추측값을 계산
    = x와 W가 여러 개

 

- Hypothesis Function : Matrix 

  • matmul() 로 여러 개의 변수를 한 번에 계산
    1. 더 간결
    2. x 의 길이가 바뀌어도 코드를 바꿀 일이 없음
    3. 속도 빠름
# naive
hypothesis = x1_train * w1 + x2_train * w2 + x3_train * w3 + b

# matrix
hypothesis = x_train.matmul(W) + b # or .mm or @

 

- Cost Function : MSE, Gradient Descent with torch.optim

  • 기존 simple linear regression과 동일한 방식
  • 데이터 정의와 W 정의 외에는 다른 점 없음

 

- Full Code 1

# 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. 모델 초기화
W = torch.zeros((3, 1), requires_grad=True)
b = torch.zeros(1, requires_grad=True)

# 3. optimizer 설정
optimizer = optim.SGD([W, b], lr=1e-5)

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

    # 4. H(x) 계산
    hypothesis = x_train.matmul(W) + b # or .mm or @
     
    # 5. cost 계산
    cost = torch.mean((hypothesis - y_train) ** 2)
     
    # 6. gradient descent : cost로 H(x) 개선
    optimizer.zero_grad()
    cost.backward()
    optimizer.step()
     
    print('Epoch {:4d}/{} hypothesis: {} Cost: {:.6f}'.format(
        epoch, nb_epochs, hypothesis.squeeze().detach(), cost.item()
    ))

 

- nn.Module

  • nn.Module 을 상속해서 모델 생성
  • nn.Linear(3, 1)
    입력 차원 : 3
    출력 차원 : 1
  • forward() : Hypothesis 계산
  • backward() : Gradient 계산 (PyTorch가 알아서 함)
'''
W = torch.zeros((3, 1), requires_grad=True)
b = torch.zeros(1, requires_grad=True)

hypothesis = x_train.matmul(W) + b 
'''

import torch.nn as nn

class MultivariateLinearRegressionModel(nn.Module):
    def __init__(self):
        super().__init__()
        self.linear = nn.Linear(3, 1)
        
    def forward(self, x):
        return self.linear(x)

hypothesis = model(x_train)

 

- F.mse_loss

  • torch.nn.functional에서 제공하는 loss function
  • 쉽게 다른 loss와 교체 가능 (l1_loss, smooth_l1_loss 등)
import torcch.nn.functional as F

# cost = torch.mean((hypothesis - y_train) ** 2)
cost = F.mse_loss(prediction, y_train)

 

- Full Code 2

  • 2. 모델정의
    4. Hypothesis 계산
    5. Cost 계산 (MSE) 
    코드 부분 변경
# 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([W, b], lr=1e-5)

nb_epochs = 20

for epoch in range(nb_epochs + 1):

    # 4. H(x) 계산
    hypothesis = model(x_train)
     
    # 5. cost 계산
    cost = F.mse_loss(prediction, y_train)
     
    # 6. gradient descent : cost로 H(x) 개선
    optimizer.zero_grad()
    cost.backward()
    optimizer.step()
    
    print('Epoch {:4d}/{} hypothesis: {} Cost: {:.6f}'.format(
        epoch, nb_epochs, hypothesis.squeeze().detach(), cost.item()
    ))