Pytorch_Multivariable_Linear_regression

Pytorch Multivariable Linear regression 기본 정리

모두를 위한 딥러닝 - 파이토치 강의 참고

  • 두 개 이상의 x값으로부터 y값을 예측하는 간단한 모델을 만들어보자.

  • 간단한 예제를 위해 (5,3) 의 train_x data를, (5,1) 의 train_y 데이터를 만든다.

1
2
3
4
5
6
x_train = torch.FloatTensor([[73, 80, 75],
[93, 88, 83],
[89, 91, 90],
[96,98, 100],
[73, 66, 70]])
y_train = torch.FloatTensor([[152], [185], [180], [196], [142]])
  • 선형 회귀 모델을 만들것이므로 우리가 학습해야하는 변수는 w 와 b 두 가지이다. 이를 torch.zeros 를 이용해 만들고 requires_grad=True 로 설정해 학습할 데이터로 설정하자.
1
2
w = torch.zeros((3,1), requires_grad=True)
b = torch.zeros(1, requires_grad=True)
  • 모델을 통해 구한 hypothesis와 실제값의 차이로부터 loss를 구하기 위해 MSE를 사용하고, SGD optimizer를 통해 w 와 b를 개선한다.
1
optimizer = torch.optim.SGD([w,b], lr=1e-5)
  • epochs 수만큼 모델을 학습시킨다.
1
2
3
4
5
6
7
8
9
10
11
12
13
for epoch in range(epochs+1):

hypothesis = x_train.matmul(w) + b # 모델을 통해 구해지는 predict값

loss = torch.mean((hypothesis - y_train) ** 2) # predict와 train 데이터로부터 구하는 loss

optimizer.zero_grad # gradient 초기화
loss.backward() # gradient 계산
optimizer.step() # w 와 b 개선

print('Epoch {:4d}/{} hypothesis : {} Cost : {:.6f}'. format(
epoch, epochs, hypothesis.squeeze().detach(), loss.item()
))

Full Code

Full Code

Comments

Your browser is out-of-date!

Update your browser to view this website correctly. Update my browser now

×