Loss used in RetinaNet for dense detection: https://arxiv.org/abs/1708.02002. Args: inputs: A float tensor of arbitrary shape. The predictions for each example. targets: A float tensor with the same shape as inputs. Stores the binary classifi
(inputs, targets, alpha: float = 0.25, gamma: float = 2)
| 24 | return loss.mean() |
| 25 | |
| 26 | def sigmoid_focal_loss(inputs, targets, alpha: float = 0.25, gamma: float = 2): |
| 27 | """ |
| 28 | Loss used in RetinaNet for dense detection: https://arxiv.org/abs/1708.02002. |
| 29 | Args: |
| 30 | inputs: A float tensor of arbitrary shape. |
| 31 | The predictions for each example. |
| 32 | targets: A float tensor with the same shape as inputs. Stores the binary |
| 33 | classification label for each element in inputs |
| 34 | (0 for the negative class and 1 for the positive class). |
| 35 | alpha: (optional) Weighting factor in range (0,1) to balance |
| 36 | positive vs negative examples. Default = -1 (no weighting). |
| 37 | gamma: Exponent of the modulating factor (1 - p_t) to |
| 38 | balance easy vs hard examples. |
| 39 | Returns: |
| 40 | Loss tensor |
| 41 | """ |
| 42 | |
| 43 | prob = inputs.sigmoid() |
| 44 | ce_loss = F.binary_cross_entropy_with_logits(inputs, targets, reduction="none") |
| 45 | p_t = prob * targets + (1 - prob) * (1 - targets) |
| 46 | loss = ce_loss * ((1 - p_t) ** gamma) |
| 47 | |
| 48 | if alpha >= 0: |
| 49 | alpha_t = alpha * targets + (1 - alpha) * (1 - targets) |
| 50 | loss = alpha_t * loss |
| 51 | return loss.mean() |
| 52 | |
| 53 | |
| 54 | class CGFormer(nn.Module): |