본문 바로가기

명사 美 비격식 (무리 중에서) 아주 뛰어난[눈에 띄는] 사람[것]

이론

손실함수 종류 loss, criterion: BCEWithLogitsLoss CrossEntropyLoss BCEWithLogitsLoss MSELoss HuberLoss


손실 함수

모델이 얼마나 틀렸는지 계산하는 함수

이진분류 MLP, CNN, LSTM BCEWithLogitsLoss
다중분류 MLP, CNN, LSTM CrossEntropyLoss
다중라벨분류 MLP, CNN, LSTM BCEWithLogitsLoss
회귀 MLP, LSTM MSELoss
이상치 있는 회귀 MLP, LSTM HuberLoss
이미지 분류 CNN CrossEntropyLoss
NLP 분류 LSTM, Transformer CrossEntropyLoss
객체 탐지 YOLO, Faster R-CNN 전용 Loss
이미지 생성 GAN, VAE, Diffusion 전용 Loss

 

 

 


이진분류 nn.BCELoss() Binary Cross Entropy Loss, sigmoid()를 거친 확률값이어야한다.

import torch
import torch.nn as nn

loss_fn = nn.BCELoss()

pred = torch.tensor([0.8])
target = torch.tensor([1.0])

loss = loss_fn(pred, target)

print(loss)
model = nn.Sequential(
    nn.Linear(10, 1),
    nn.Sigmoid()
)

criterion = nn.BCELoss()

 

 

이진분류  nn.BCEWithLogitsLoss() 실무에서 더 많이 사용한다.  내부적으로 sigmoid와 BCE를 한번에 계산해  코드간결 + 안정적 + overflow 방지 + 학습도 잘됨

import torch
import torch.nn as nn

criterion = nn.BCEWithLogitsLoss()

logits = torch.tensor([2.0])
target = torch.tensor([1.0])

loss = criterion(logits, target)

print(loss)
model = nn.Sequential(
    nn.Linear(10, 1)
)

criterion = nn.BCEWithLogitsLoss()

 

 

 

다중분류 nn.CrossEntropyLoss(), 내부에 softmax 와 nllloss 가 포함되어있다. 

import torch
import torch.nn as nn

criterion = nn.CrossEntropyLoss()

logits = torch.tensor([[2.5, 0.3, -1.2]])

target = torch.tensor([0])

loss = criterion(logits, target)

print(loss)
model = nn.Sequential(
    nn.Linear(10, 3)
)

criterion = nn.CrossEntropyLoss()

 

 

이진 분류 1 Sigmoid (또는 없음) BCEWithLogitsLoss 권장
다중 분류 클래스 수만큼 없음 CrossEntropyLoss
다중 라벨 분류 클래스 수만큼 없음 BCEWithLogitsLoss

 

 

 

 

회귀용으로는 MSELoss를 사용한다. 집값예측, 온도예측, 주가예측 등에 사용. 출력이 연속적인 숫자일때 사용한다. 

Mean Squared Error 평균제곱오차.

import torch
import torch.nn as nn

criterion = nn.MSELoss()

pred = torch.tensor([8.0])
target = torch.tensor([10.0])

loss = criterion(pred, target)

print(loss)

 

 

 

 

HuberLoss 

이상치가 있을때 MSELoss보다 강하다. 회귀문제에서 사용하는 손실함수 오차를 제곱함으로 모델이 이상치 하나에 지나치게 끌려갈 수있는데 HuberLoss는 작은 오차는 제곱, 큰 오차는 절대값으로 계산한다. 작은 오차는 민감하게, 큰 이상치에는 과하게 흔들리지않도록 하며 회귀 문제에서 이상치가 섞여있을때 유용하다. criterion = nn.HuberLoss(),

import torch
import torch.nn as nn

criterion = nn.HuberLoss()

pred = torch.tensor([2.5, 3.0])
target = torch.tensor([3.0, 4.0])

loss = criterion(pred, target)

print(loss)