옵티마이저, 학습, 평가

PyTorch로 배우는 Intermediate Deep Learning

Michal Oleszak

Machine Learning Engineer

학습 루프

import torch.nn as nn
import torch.optim as optim

criterion = nn.BCELoss()
optimizer = optim.SGD(net.parameters(), lr=0.01)


for epoch in range(1000): for features, labels in dataloader_train:
optimizer.zero_grad()
outputs = net(features)
loss = criterion( outputs, labels.view(-1, 1) )
loss.backward()
optimizer.step()
  • 손실 함수와 옵티마이저 정의
    • 이진 분류에는 BCELoss
    • 옵티마이저: SGD
  • 에폭과 학습 배치를 반복
  • 그래디언트 초기화
  • 순전파: 모델 출력 계산
  • 손실 계산
  • 그래디언트 계산
  • 옵티마이저 스텝: 파라미터 업데이트
PyTorch로 배우는 Intermediate Deep Learning

옵티마이저의 동작 방식

 

길이 2의 두 벡터: 하나는 파라미터 값(1, 0.5), 다른 하나는 그래디언트(0.9, -0.2)

PyTorch로 배우는 Intermediate Deep Learning

옵티마이저의 동작 방식

 

화살표가 파라미터와 그래디언트 벡터가 과녁 모양의 옵티마이저로 들어감을 표시

PyTorch로 배우는 Intermediate Deep Learning

옵티마이저의 동작 방식

 

옵티마이저에서 두 파라미터 업데이트(-0.5, 0.5) 벡터로 향하는 화살표

PyTorch로 배우는 Intermediate Deep Learning

옵티마이저의 동작 방식

 

파라미터 업데이트에서 0.5와 1.0의 새 값으로 향하는 화살표

PyTorch로 배우는 Intermediate Deep Learning

옵티마이저의 동작 방식

 

파라미터 업데이트에서 0.5와 1.0의 새 값으로 향하는 화살표

PyTorch로 배우는 Intermediate Deep Learning

확률적 경사하강법(SGD)

optimizer = optim.SGD(net.parameters(), lr=0.01)
  • 업데이트는 학습률에 좌우됨
  • 단순·효율적, 기본 모델에 적합
  • 실제로는 드물게 사용
PyTorch로 배우는 Intermediate Deep Learning

Adaptive Gradient(Adagrad)

optimizer = optim.Adagrad(net.parameters(), lr=0.01)
  • 파라미터별로 학습률을 적응적으로 조정
  • 희소 데이터에 유리
  • 학습률이 너무 빨리 감소할 수 있음
PyTorch로 배우는 Intermediate Deep Learning

Root Mean Square Propagation(RMSprop)

optimizer = optim.RMSprop(net.parameters(), lr=0.01)
  • 각 파라미터의 과거 그래디언트 크기에 따라 업데이트
PyTorch로 배우는 Intermediate Deep Learning

Adaptive Moment Estimation(Adam)

optimizer = optim.Adam(net.parameters(), lr=0.01)
  • 가장 범용적이며 널리 사용
  • RMSprop + 그래디언트 모멘텀
  • 기본 선택으로 자주 사용
PyTorch로 배우는 Intermediate Deep Learning

모델 평가

from torchmetrics import Accuracy

acc = Accuracy(task="binary")


net.eval() with torch.no_grad(): for features, labels in dataloader_test:
outputs = net(features)
preds = (outputs >= 0.5).float()
acc(preds, labels.view(-1, 1))
accuracy = acc.compute() print(f"Accuracy: {accuracy}")
Accuracy: 0.6759443283081055
  • 정확도(metric) 설정
  • 평가 모드로 전환, 테스트 배치를 no-grad로 반복
  • 모델로 예측 확률 계산
  • 예측 레이블 산출
  • 정확도 metric 업데이트
PyTorch로 배우는 Intermediate Deep Learning

Vamos praticar!

PyTorch로 배우는 Intermediate Deep Learning

Preparing Video For Download...