본문 바로가기

Activities/메타코드 서포터즈 4기

[Optimizer] 메타코드 강의 후기_챕터2: Pytorch Fundamentals - Loss 실습하기

저번 시간에 공부했던 Loss function 이랑 Optimization 방식들을 실제 실습으로 적용해보면서 공부하도록 하자. 

 

 

 

4. Loss Function 

MSE Loss 

: Regression Task에 주로 사용하며, predict값 과 실제 output값의 차이를 제곱합으로 계산한다. 

import torch.nn as nn 

#nn.MSELoss() 
mse_loss = nn.MSELoss()
pred = torch.randn(4,10)
output = torch.randn(4, 10)
mse_loss(pred, output) 

print(pred, output)

 

 

nn.NLLLoss() : Negative Log Likelihood Loss 

실제결과와 예측 확률을 곱한 것을 더해서 로그를 씌운 것이다. 

Softmax에 Log를 씌운 형태를 구현한 LogSoftmax 함수와 함께 사용하면 Cross Entropy Loss와 같아진다. 

 

왜 LogSoftmax를 쓰는가? 

nn.LogSoftmax() 와 torch.log(nn.Softmax())가 결과값은 같기는 하지만,

softmax에 의한 결과는 불안정하기 때문에 NLL Loss에서 직접적으로 사용되지는 않는다. 

따라서 전자의 방법을 사용하도록 하자. 

 

pred = torch.randn([3, 5], requires_grad = True) 
print(pred) 
output = torch.tensor([1, 0, 3]) # [0,4] 사이 class label 

print(m(pred))
print(nll_loss(m(pred), output))

 

output = torch.tensor([1, 0, 3]) 가 의미하는 바를 알기 

[0, 1, 0, 0, 0]

[1, 0, 0, 0, 0]

[0, 0, 0, 1, 0]

 

앞에 NLLLoss 를 배우긴 하였으나 CrossEntropyLoss()는

NLLLoss + softmax 가 한번에 구현되어 있기 때문에 전자를 굳이 쓰지 않아도 된다.

pred = torch.randn(3, 5, required_grad=True) 
print(pred.shape)
print(pred)

output = torch.tensor([0, 4, 0], dtype=torch.long) #[0,4] 사이 class label 
print(output.shape) 

ce_loss(pred, output)

output = torch.tensor([0, 4, 0], dtype=torch.long) 의 의미는 

[1, 0, 0, 0, 0]

[0, 0, 0, 0, 1]

[1, 0, 0, 0, 0]

 

두가지 방식으로 할  수 있는데, 

output 값을 확률값으로도 나오게 할 수 있다. 

 

# Example of target with class probabilities 
pred = torch.randn(3, 4, requires_grad=True) 
output = torch.randn(3,4).softmax(dim=1) #output 이 확률값인 경우 

print(output) 
ce_loss(pred, output)

 

 

5. Loss 최적화 

torch.optim — PyTorch 2.3 documentation

 

torch.optim — PyTorch 2.3 documentation

torch.optim torch.optim is a package implementing various optimization algorithms. Most commonly used methods are already supported, and the interface is general enough, so that more sophisticated ones can also be easily integrated in the future. How to us

pytorch.org

 

위 링크에 구현되어 있는 optimizer들이 많다. 직접 들어가면 알고리즘을 더 상세히 확인할 수 있다. 

기술문서에 자주 들어가서 보는 습관을 기르도록 합시다. 

 

실제로 잘 활용할 두가지 방식만 배워보도록 하자. 

 

SGD : Stocastic Gradient Descent 

데이터 중 일부만 샘플링하여 gradient를 계산함으로써 효율적으로 연산이 가능하다. 

 

#SGD
sgd_optimizer = torch.optim.SGD(model.parameters(), lr=0.01, momentum=0.9)

 

ADAM : RMSProp + Momentum 

Gradient로 업데이트하는 step의 size와 방향을 모두 고려하여 update하는 방식이다. 

 

#ADAM
adam_optimizer = torch.optim.ADAM(model, lr=0.01, betas=(0.9, 0.999))

 


메타코드 4기 서포터즈 활동의 일환으로 작성한 게시글입니다. 

메타코드M (mcode.co.kr)