import torch
x_train = torch.FloatTensor([[1,1], [2,2], [3,3]]) # 파이토치 trin 선언 방식
y_train = torch.FloatTensor([[10], [20], [30]])
w = torch.randn([2,1], requires_grad=True) # 행렬 곱셈을 위한 W, B 생성 방식
b = torch.randn([1], requires_grad=True)
optimizer = torch.optim.SGD([w, b], lr=0.01) # 모델의 옵티마이져를 지정.
# 딥러링 1단계 모델을 만든다 Model Setup
def H(x):
model = torch.matmul(x, w) + b # 모델을 선언 후 행열을 곱하기 위한 방식.
return model
# 딥러링 2단계 모델을 학습시킨다. Training
for iter in range(2000):
cost = torch.mean((H(x_train) - y_train)**2) # W,B 값을 모두 구하기 위해.
optimizer.zero_grad() # 0으로 가기위해 / 편미분을 위해 세 문장은 같이 다님
cost.backward() # w, b 값을 업데이트 한다.
optimizer.step()
if iter % 100 == 0:
print(iter, cost.detach().item())
# 딥러링 3단계 추론을 수행한다. Inference
x_test = torch.FloatTensor([[4,4]]) # 새로운 상수값(y_train)인 x_test의 값에 W, B으로 값을 구함
model_result = H(x_test)
print(model_result)
print(model_result.detach())
print(model_result.detach().item())
0 608.9104614257812
100 0.9146091341972351
200 0.5418955683708191
300 0.3210658133029938
400 0.1902281790971756
500 0.11270727962255478
600 0.06677782535552979
700 0.039565082639455795
800 0.02344209887087345
900 0.013889129273593426
1000 0.008229226805269718
1100 0.004875602666288614
1200 0.0028887682128697634
1300 0.0017115663504227996
1400 0.0010141038801521063
1500 0.0006008404307067394
1600 0.0003559827746357769
1700 0.000210936923394911
1800 0.00012498983414843678
1900 7.405867654597387e-05
tensor([[39.9871]], grad_fn=<AddBackward0>)
tensor([[39.9871]])
39.987060546875