balanced_l1_loss.py 1.84 KB
Newer Older
Kai Chen's avatar
Kai Chen committed
1
2
import numpy as np
import torch
3
4
import torch.nn as nn

5
from .utils import weighted_loss
6
7
8
from ..registry import LOSSES


Kai Chen's avatar
Kai Chen committed
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
@weighted_loss
def balanced_l1_loss(pred,
                     target,
                     beta=1.0,
                     alpha=0.5,
                     gamma=1.5,
                     reduction='mean'):
    assert beta > 0
    assert pred.size() == target.size() and target.numel() > 0

    diff = torch.abs(pred - target)
    b = np.e**(gamma / alpha) - 1
    loss = torch.where(
        diff < beta, alpha / b *
        (b * diff + 1) * torch.log(b * diff / beta + 1) - alpha * diff,
        gamma * diff + gamma / b - alpha * beta)

    return loss


29
30
31
32
33
34
35
@LOSSES.register_module
class BalancedL1Loss(nn.Module):
    """Balanced L1 Loss

    arXiv: https://arxiv.org/pdf/1904.02701.pdf (CVPR 2019)
    """

Kai Chen's avatar
Kai Chen committed
36
37
38
39
40
41
    def __init__(self,
                 alpha=0.5,
                 gamma=1.5,
                 beta=1.0,
                 reduction='mean',
                 loss_weight=1.0):
42
43
44
45
        super(BalancedL1Loss, self).__init__()
        self.alpha = alpha
        self.gamma = gamma
        self.beta = beta
Kai Chen's avatar
Kai Chen committed
46
        self.reduction = reduction
47
48
        self.loss_weight = loss_weight

49
50
51
52
53
54
55
56
57
58
    def forward(self,
                pred,
                target,
                weight=None,
                avg_factor=None,
                reduction_override=None,
                **kwargs):
        assert reduction_override in (None, 'none', 'mean', 'sum')
        reduction = (
            reduction_override if reduction_override else self.reduction)
Kai Chen's avatar
Kai Chen committed
59
        loss_bbox = self.loss_weight * balanced_l1_loss(
60
61
62
63
64
65
            pred,
            target,
            weight,
            alpha=self.alpha,
            gamma=self.gamma,
            beta=self.beta,
66
            reduction=reduction,
Kai Chen's avatar
Kai Chen committed
67
            avg_factor=avg_factor,
68
69
            **kwargs)
        return loss_bbox