losses.py 3.66 KB
Newer Older
Kai Chen's avatar
Kai Chen committed
1
# TODO merge naive and weighted loss.
pangjm's avatar
pangjm committed
2
3
4
5
import torch
import torch.nn.functional as F


Kai Chen's avatar
Kai Chen committed
6
7
8
9
10
def weighted_nll_loss(pred, label, weight, avg_factor=None):
    if avg_factor is None:
        avg_factor = max(torch.sum(weight > 0).float().item(), 1.)
    raw = F.nll_loss(pred, label, reduction='none')
    return torch.sum(raw * weight)[None] / avg_factor
pangjm's avatar
pangjm committed
11
12


yhcao6's avatar
yhcao6 committed
13
def weighted_cross_entropy(pred, label, weight, avg_factor=None,
yhcao6's avatar
rename  
yhcao6 committed
14
                           reduce=True):
Kai Chen's avatar
Kai Chen committed
15
16
17
    if avg_factor is None:
        avg_factor = max(torch.sum(weight > 0).float().item(), 1.)
    raw = F.cross_entropy(pred, label, reduction='none')
yhcao6's avatar
rename  
yhcao6 committed
18
    if reduce:
yhcao6's avatar
yhcao6 committed
19
        return torch.sum(raw * weight)[None] / avg_factor
yhcao6's avatar
yhcao6 committed
20
    else:
yhcao6's avatar
yhcao6 committed
21
        return raw * weight / avg_factor
pangjm's avatar
pangjm committed
22
23


Kai Chen's avatar
Kai Chen committed
24
25
26
def weighted_binary_cross_entropy(pred, label, weight, avg_factor=None):
    if avg_factor is None:
        avg_factor = max(torch.sum(weight > 0).float().item(), 1.)
pangjm's avatar
pangjm committed
27
28
    return F.binary_cross_entropy_with_logits(
        pred, label.float(), weight.float(),
Kai Chen's avatar
Kai Chen committed
29
        reduction='sum')[None] / avg_factor
pangjm's avatar
pangjm committed
30
31
32
33
34
35
36


def sigmoid_focal_loss(pred,
                       target,
                       weight,
                       gamma=2.0,
                       alpha=0.25,
Kai Chen's avatar
Kai Chen committed
37
                       reduction='elementwise_mean'):
pangjm's avatar
pangjm committed
38
39
40
41
42
    pred_sigmoid = pred.sigmoid()
    pt = (1 - pred_sigmoid) * target + pred_sigmoid * (1 - target)
    weight = (alpha * target + (1 - alpha) * (1 - target)) * weight
    weight = weight * pt.pow(gamma)
    return F.binary_cross_entropy_with_logits(
Kai Chen's avatar
Kai Chen committed
43
        pred, target, weight, reduction=reduction)
pangjm's avatar
pangjm committed
44
45
46
47
48
49
50


def weighted_sigmoid_focal_loss(pred,
                                target,
                                weight,
                                gamma=2.0,
                                alpha=0.25,
Kai Chen's avatar
Kai Chen committed
51
                                avg_factor=None,
pangjm's avatar
pangjm committed
52
                                num_classes=80):
Kai Chen's avatar
Kai Chen committed
53
54
    if avg_factor is None:
        avg_factor = torch.sum(weight > 0).float().item() / num_classes + 1e-6
pangjm's avatar
pangjm committed
55
56
    return sigmoid_focal_loss(
        pred, target, weight, gamma=gamma, alpha=alpha,
Kai Chen's avatar
Kai Chen committed
57
        reduction='sum')[None] / avg_factor
pangjm's avatar
pangjm committed
58
59
60
61
62
63
64


def mask_cross_entropy(pred, target, label):
    num_rois = pred.size()[0]
    inds = torch.arange(0, num_rois, dtype=torch.long, device=pred.device)
    pred_slice = pred[inds, label].squeeze(1)
    return F.binary_cross_entropy_with_logits(
65
        pred_slice, target, reduction='elementwise_mean')[None]
pangjm's avatar
pangjm committed
66
67


Kai Chen's avatar
Kai Chen committed
68
def smooth_l1_loss(pred, target, beta=1.0, reduction='elementwise_mean'):
pangjm's avatar
pangjm committed
69
70
71
72
73
    assert beta > 0
    assert pred.size() == target.size() and target.numel() > 0
    diff = torch.abs(pred - target)
    loss = torch.where(diff < beta, 0.5 * diff * diff / beta,
                       diff - 0.5 * beta)
Kai Chen's avatar
Kai Chen committed
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
    reduction = F._Reduction.get_enum(reduction)
    # none: 0, elementwise_mean:1, sum: 2
    if reduction == 0:
        return loss
    elif reduction == 1:
        return loss.sum() / pred.numel()
    elif reduction == 2:
        return loss.sum()


def weighted_smoothl1(pred, target, weight, beta=1.0, avg_factor=None):
    if avg_factor is None:
        avg_factor = torch.sum(weight > 0).float().item() / 4 + 1e-6
    loss = smooth_l1_loss(pred, target, beta, reduction='none')
    return torch.sum(loss * weight)[None] / avg_factor
pangjm's avatar
pangjm committed
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105


def accuracy(pred, target, topk=1):
    if isinstance(topk, int):
        topk = (topk, )
        return_single = True

    maxk = max(topk)
    _, pred_label = pred.topk(maxk, 1, True, True)
    pred_label = pred_label.t()
    correct = pred_label.eq(target.view(1, -1).expand_as(pred_label))

    res = []
    for k in topk:
        correct_k = correct[:k].view(-1).float().sum(0, keepdim=True)
        res.append(correct_k.mul_(100.0 / pred.size(0)))
    return res[0] if return_single else res