Scheaven
2021-09-18 291deeb1fcf45dbf39a24aa72a213ff3fd6b3405
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
U
¹_Ÿã@sRdZddlZddlmmZd
ejejeeeejdœdd„Z    Gdd    „d    e
ƒZ dS) z:
@author:  xingyu liao
@contact: sherlockliao01@gmail.com
éNç@Úmean)ÚinputÚtargetÚalphaÚgammaÚ    reductionÚreturnc Cs†t |¡std t|ƒ¡ƒ‚t|jƒdks:td |j¡ƒ‚| d¡| d¡krjtd | d¡| d¡¡ƒ‚| d¡}|f| ¡dd…}| ¡dd…| ¡dd…kr¾td || ¡¡ƒ‚|j    |j    ksÞtd     |j    |j    ¡ƒ‚t
j |dd
}t
j ||jdd }t  | d |¡}    | |    t |¡}
tj||
dd
} |d krH| } n:|dkr^t | ¡} n$|dkrtt | ¡} ntd |¡ƒ‚| S)zhFunction that computes Focal loss.
    See :class:`fastreid.modeling.losses.FocalLoss` for details.
    z(Input type is not a torch.Tensor. Got {}éz-Invalid input shape, we expect BxCx*. Got: {}rz?Expected input batch_size ({}) to match target batch_size ({}).NézExpected target size {}, got {}z4input and target must be in the same device. Got: {})Údim)Ú num_classesgð?ÚnonerÚsumzInvalid reduction mode: {})ÚtorchÚ    is_tensorÚ    TypeErrorÚformatÚtypeÚlenÚshapeÚ
ValueErrorÚsizeÚdeviceÚFÚsoftmaxÚone_hotÚpowÚlogrrÚNotImplementedError) rrrrrÚnÚout_sizeZ
input_softZtarget_one_hotÚweightÚfocalZloss_tmpÚloss©r%ú./modeling/losses/focal_loss.pyÚ
focal_losssT    
ÿÿÿ
 ÿ ÿÿ
 
 
 ÿr'c@s.eZdZdZdd„Zejejedœdd„ZdS)Ú    FocalLossuÿCriterion that computes Focal loss.
    According to [1], the Focal loss is computed as follows:
    .. math::
        \text{FL}(p_t) = -\alpha_t (1 - p_t)^{\gamma} \, \text{log}(p_t)
    where:
       - :math:`p_t` is the model's estimated probability for each class.
    Arguments:
        alpha (float): Weighting factor :math:`\alpha \in [0, 1]`.
        gamma (float): Focusing parameter :math:`\gamma >= 0`.
        reduction (str, optional): Specifies the reduction to apply to the
         output: â€˜none’ | â€˜mean’ | â€˜sum’. â€˜none’: no reduction will be applied,
         â€˜mean’: the sum of the output will be divided by the number of elements
         in the output, â€˜sum’: the output will be summed. Default: â€˜none’.
    Shape:
        - Input: :math:`(N, C, *)` where C = number of classes.
        - Target: :math:`(N, *)` where each value is
          :math:`0 â‰¤ targets[i] â‰¤ C−1`.
    Examples:
        >>> N = 5  # num_classes
        >>> loss = FocalLoss(cfg)
        >>> input = torch.randn(1, N, 3, 5, requires_grad=True)
        >>> target = torch.empty(1, 3, 5, dtype=torch.long).random_(N)
        >>> output = loss(input, target)
        >>> output.backward()
    References:
        [1] https://arxiv.org/abs/1708.02002
    cCs.|jjjj|_|jjjj|_|jjjj|_dS)N)    ÚMODELÚLOSSESZFLÚALPHAÚ_alphaZGAMMAÚ_gammaÚSCALEÚ_scale)ÚselfÚcfgr%r%r&Ú__init__eszFocalLoss.__init__)Úpred_class_logitsÚ
gt_classesr    cCs t|||j|jƒ}d||jiS)NZ
loss_focal)r'r,r-r/)r0r3Ú_r4r$r%r%r&Ú__call__jsÿzFocalLoss.__call__N)    Ú__name__Ú
__module__Ú __qualname__Ú__doc__r2rÚTensorÚdictr6r%r%r%r&r(Fsr()rr) r:rÚtorch.nn.functionalÚnnÚ
functionalrr;ÚfloatÚstrr'Úobjectr(r%r%r%r&Ú<module>s
ûû 8