[인공지능] 3주차(실습) | 다중선형회귀 (multivariate Linear Regression)

dusruddl2·2022년 10월 16일

SJU_인공지능

목록 보기
10/23

라이브러리 Imports

import torch
import torch.optim as optim
# For reproducibility
torch.manual_seed(1)

학습 데이터: 단순 데이터 (데이터 표현 1.)

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

feature의 개수가 앞선 단일회귀문제에서는 1개였는데 3개로 늘었음

단순 데이터를 이용한 모델 학습

# 모델 초기화
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 = x1_train * w1 + x2_train * w2 + x3_train * w3 + b

    # cost 계산
    cost = torch.mean((hypothesis - y_train) ** 2)

    # cost로 H(x) 개선
    optimizer.zero_grad()
    cost.backward()
    optimizer.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()
        ))

설마 이렇게 하는 사람 없지? 당연히 Matrix이용해야지


학습 데이터: 행렬 데이터 (데이터 표현 2.)

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]])
print(x_train.shape)
print(y_train.shape)

✅ 행렬 데이터를 이용한 모델 학습

# 모델 초기화
W = torch.zeros([5,1], requires_grad = True)
b = torch.zeros(1, requires_grad = True)

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

nb_epochs = 20
for epoch in range(nb_epochs+1):
	# H(x) 계산
    # Matrix 연산
    hypothesis = x_train.matmul(W) + b
    
    #cost 계산
    cost = torch.mean((hypothesis-y_train)**2)
    
    #cost로 H(x) 갱신
    optimizer.zero_grad()
    cost.backward()
    optimizer.step()
    
    # 100번마다 로그 출력
    if epoch%100 == 0
    print('Epoch: {:4d}/{}, W: {:.3f}, b: {:.3f}, Cost: {:.6f}.format(
    epoch, nb_epochs, W.item(), b.item(), cost.item()
    ))

print(W)
print(b)

profile
정리된 글은 https://dusruddl2.tistory.com/로 이동

0개의 댓글