HealthyAI

DL) Loss Function 본문

AI/Deep Learning

DL) Loss Function

BiteApple 2023. 4. 20. 01:51
반응형

 

Focal Loss

  • Focal Loss는 Imbalanced Data 문제를 해결하기 위한 손실함수에요.
  • Object Detection 모델 중 1 stage detector (YOLO, SSD) 와 같이 anchor box를 활용해 dense prediction을 하는 모델들은 현재까지 사용하고 있는 Loss function 이에요.

 

ref:Focal Loss

CE Loss 의 한계

  • CE Loss 는 모든 sample 에 대한 예측 결과에 동등한 가중치를 둔다는 점이 단점이에요.
  • Foreground 와 Background 모두 같은 Loss 값을 가진다는 것이 문제에요.
  • Background 케이스의 수가 훨씬 더 많기 때문에 같은 비율로 Loss 값이 업데이트되면 Background 에 대해 학습이 훨씬 더 많이 되고 이것이 계속 누적된다면 Foreground에 대한 학습량이 현저히 줄어들어요.
  • object detection task 에서 1stage detector 들은 한장의 이미지에 대해 소수의 객체에 대한 예측과 정답이 아닌 background 예측값들이 비정상 적으로 많아요.

 

Focal Loss 는

  • Easy example 의 weight를 줄이고 Hard negative example 에 대한 학습에 초점을 맞춰요.
  • FL 선들이 CE 선 보다 아래에 있다. Loss 자체는 FL 이 더 낮다는 것을 알 수 있어요.
    • 확률이 높을수록 낮은 loss, 낮을수록 비교적 큰 loss 를 갖게 된다.예측 확률값이 낮을 때에 비해 확률이 높아질수록 loss 값이급격하게 낮게 설정돼요.
import torch
import torch.nn as nn

class FocalLoss(nn.Module):
    def __init__(self, weight=None,
                 gamma=2., reduction='mean'):
        nn.Module.__init__(self)
        self.weight = weight
        self.gamma = gamma
        self.reduction = reduction

    def forward(self, input_tensor, target_tensor):
        log_prob = F.log_softmax(input_tensor, dim=-1)
        prob = torch.exp(log_prob)
        return F.nll_loss(
            ((1 - prob) ** self.gamma) * log_prob,
            target_tensor,
            weight=self.weight,
            reduction=self.reduction
        )

 

Label Smoothing Loss

  • Label Smoothing은 학습 데이터의 representation을 더 잘나타내는데 도움을 줘요.
class LabelSmoothingLoss(nn.Module):
    def __init__(self, classes=3, smoothing=0.0, dim=-1):
        super(LabelSmoothingLoss, self).__init__()
        self.confidence = 1.0 - smoothing
        self.smoothing = smoothing
        self.cls = classes
        self.dim = dim

    def forward(self, pred, target):
        pred = pred.log_softmax(dim=self.dim)
        with torch.no_grad():
            true_dist = torch.zeros_like(pred)
            true_dist.fill_(self.smoothing / (self.cls - 1))
            true_dist.scatter_(1, target.data.unsqueeze(1), self.confidence)
        return torch.mean(torch.sum(-true_dist * pred, dim=self.dim))

 

F1 Loss

  • F1 Loss는 F1 score 향상을 목적으로 하는 손실함수에요.
class F1Loss(nn.Module):
    def __init__(self, classes=3, epsilon=1e-7):
        super().__init__()
        self.classes = classes
        self.epsilon = epsilon
    def forward(self, y_pred, y_true):
        assert y_pred.ndim == 2
        assert y_true.ndim == 1
        y_true = F.one_hot(y_true, self.classes).to(torch.float32)
        y_pred = F.softmax(y_pred, dim=1)

        tp = (y_true * y_pred).sum(dim=0).to(torch.float32)
        tn = ((1 - y_true) * (1 - y_pred)).sum(dim=0).to(torch.float32)
        fp = ((1 - y_true) * y_pred).sum(dim=0).to(torch.float32)
        fn = (y_true * (1 - y_pred)).sum(dim=0).to(torch.float32)

        precision = tp / (tp + fp + self.epsilon)
        recall = tp / (tp + fn + self.epsilon)

        f1 = 2 * (precision * recall) / (precision + recall + self.epsilon)
        f1 = f1.clamp(min=self.epsilon, max=1 - self.epsilon)
        return 1 - f1.mean()
반응형

'AI > Deep Learning' 카테고리의 다른 글

DL) Regularization  (0) 2023.04.20
DL) Training Inference  (0) 2023.04.19
DL) Pre-trained Information  (0) 2023.04.02
DL) Optimization - Gradient Descent  (0) 2023.02.10