
    3j8                        S SK Jr  S SKJr  S SKrS SKJr  S SKJrJrJ	r	  S SK
Jr  S SKJr      S               SS jjr " S	 S
\R                  5      r      S                 SS jjr " S S\R                  5      rg)    )annotations)OptionalN)nn)KORNIA_CHECKKORNIA_CHECK_IS_TENSORKORNIA_CHECK_SHAPE)mask_ignore_pixels)one_hotc                   [        U / SQ5        U R                  S   4U R                  SS -   n[        U R                  S   UR                  S   :H  =(       a    UR                  SS U R                  SS :H  SU SUR                   35        [        U R                  UR                  :H  SU R                   S	UR                   35        [	        X5      u  p[        XR                  S   U R                  U R                  S
9n	Ub  UR                  S5        X-  n	U R                  S5      n
[        R                  " SU
R                  5       -
  U5      * U
-  U	-  nU R                  S   nS/S/[        U R                  SS 5      -  -   nUbM  [        R                  " SU-
  /U/US-
  -  -   UR                  UR                  S9nUR                  U5      nX-  nUb  [        US5        [        UR                  S   U:H  =(       a    UR!                  5       U:H  SU SUR                   35        [        UR                  U R                  :H  SUR                   S	U R                   35        UR                  U5      nX[-  nUS:X  a  UnU$ US:X  a  [        R"                  " U5      nU$ US:X  a  [        R$                  " U5      nU$ ['        SU 35      e)av  Criterion that computes Focal loss.

According to :cite:`lin2018focal`, 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.

Args:
    pred: logits torch.Tensor with shape :math:`(N, C, *)` where C = number of classes.
    target: labels torch.Tensor with shape :math:`(N, *)` where each value is an integer
      representing correct classification :math:`target[i] \in [0, C)`.
    alpha: Weighting factor :math:`\alpha \in [0, 1]`.
    gamma: Focusing parameter :math:`\gamma >= 0`.
    reduction: 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.
    weight: weights for classes with shape :math:`(num\_of\_classes,)`.
    ignore_index: labels with this value are ignored in the loss computation.

Return:
    the computed loss.

Example:
    >>> C = 5  # num_classes
    >>> pred = torch.randn(1, C, 3, 5, requires_grad=True)
    >>> target = torch.randint(C, (1, 3, 5))
    >>> kwargs = {"alpha": 0.5, "gamma": 2.0, "reduction": 'mean'}
    >>> output = focal_loss(pred, target, **kwargs)
    >>> output.backward()

BC*r      N   Expected target size , got 1pred and target must be in the same device. Got:  and )num_classesdevicedtype      ?)r   r   $weight must be torch.Tensor or None.)weight shape must be (num_of_classes,): (,), got 1weight and pred must be in the same device. Got: nonemeansumInvalid reduction mode: )r   shaper   r   r	   r
   r   
unsqueeze_log_softmaxtorchpowexplentensorviewr   numelr    r!   NotImplementedError)predtargetalphagamma	reductionweightignore_indexout_sizetarget_masktarget_one_hotlog_pred_softloss_tmpnum_of_classesbroadcast_dims	alpha_faclosss                   M/home/wildlama/miniconda3/lib/python3.13/site-packages/kornia/losses/focal.py
focal_lossr?   !   s   \ t_-

1$**QR.0H	A&,,q/	)	Pfll12.>$**QR..P
z~> v}}$
;DKK=fmm_]
 -VBF $+6zz!}UYU`U`hlhrhr#sN q!'5 #'"2"21"5M $iim.?.?.A(A5IIMY\jjHZZ]NTQC#djjn"555NLLYK5'^a%788W_WfWf
	 NN>2	'v'MN\\!_.S6<<>^3S77GxPVP\P\~^	
 	MMT[[(?eTXT_T_S`a	

 ^,$F K 
f	zz(#
 K	 
e	yy" K "$<YK"HII    c                  \   ^  \ rS rSrSr    S           SU 4S jjjrSS jrSrU =r$ )		FocalLoss   aA  Criterion that computes Focal loss.

According to :cite:`lin2018focal`, 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.

Args:
    alpha: Weighting factor :math:`\alpha \in [0, 1]`.
    gamma: Focusing parameter :math:`\gamma >= 0`.
    reduction: 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.
    weight: weights for classes with shape :math:`(num\_of\_classes,)`.
    ignore_index: labels with this value are ignored in the loss computation.

Shape:
    - Pred: :math:`(N, C, *)` where C = number of classes.
    - Target: :math:`(N, *)` where each value is an integer
      representing correct classification :math:`target[i] \in [0, C)`.

Example:
    >>> C = 5  # num_classes
    >>> pred = torch.randn(1, C, 3, 5, requires_grad=True)
    >>> target = torch.randint(C, (1, 3, 5))
    >>> kwargs = {"alpha": 0.5, "gamma": 2.0, "reduction": 'mean'}
    >>> criterion = FocalLoss(**kwargs)
    >>> output = criterion(pred, target)
    >>> output.backward()

c                ^   > [         TU ]  5         Xl        X l        X0l        X@l        XPl        g N)super__init__r0   r1   r2   r3   r4   )selfr0   r1   r2   r3   r4   	__class__s         r>   rG   FocalLoss.__init__   s*     	&+
!
'.4+7r@   c           	         [        XU R                  U R                  U R                  U R                  U R
                  5      $ rE   )r?   r0   r1   r2   r3   r4   rH   r.   r/   s      r>   forwardFocalLoss.forward   s1    $

DJJPTP[P[]a]n]noor@   )r0   r1   r4   r2   r3          @r   N)r0   Optional[float]r1   floatr2   strr3   Optional[torch.Tensor]r4   Optional[int]returnNoner.   torch.Tensorr/   rZ   rW   rZ   	__name__
__module____qualname____firstlineno____doc__rG   rM   __static_attributes____classcell__rI   s   @r>   rB   rB      sg    $R )-&*88 8 	8
 '8 $8 
8 8p pr@   rB   c                &   [        U / SQ5        [        U R                  UR                  :H  SU R                   SUR                   35        [        U R                  UR                  :H  SU R                   SUR                   35        [        R
                  R                  U 5      n[        R
                  R                  U * 5      n	[        X5      u  pU
b  X-  n	X-  nU	R                  5       R                  U5      * U-  U-  nUR                  5       R                  U5      * SU-
  -  U	-  nUb  X+-  nSU-
  U-  nU R                  S   nS	/S/[        U R                  S
S 5      -  -   nUb  [        US5        [        UR                  S   U:H  =(       a    UR                  5       U:H  SU SUR                   35        [        UR                  U R                  :H  SUR                   SU R                   35        UR                  U5      nX[-  nX-   nUb  [        US5        [        UR                  S   U:H  =(       a    UR                  5       U:H  SU SUR                   35        [        UR                  U R                  :H  SUR                   SU R                   35        UR                  U5      nXo-  nUS:X  a  UnU$ US:X  a  [        R                  " U5      nU$ US:X  a  [        R                   " U5      nU$ [#        SU 35      e)a  Criterion that computes Binary Focal loss.

According to :cite:`lin2018focal`, 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.

Args:
    pred: logits torch.Tensor with shape :math:`(N, C, *)` where C = number of classes.
    target: labels torch.Tensor with the same shape as pred :math:`(N, C, *)`
      where each value is between 0 and 1.
    alpha: Weighting factor :math:`\alpha \in [0, 1]`.
    gamma: Focusing parameter :math:`\gamma >= 0`.
    reduction: 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.
    pos_weight: a weight of positive examples with shape :math:`(num\_of\_classes,)`.
      It is possible to trade off recall and precision by adding weights to positive examples.
    weight: weights for classes with shape :math:`(num\_of\_classes,)`.
    ignore_index: labels with this value are ignored in the loss computation.

Returns:
    the computed loss.

Examples:
    >>> C = 3  # num_classes
    >>> pred = torch.randn(1, C, 5, requires_grad=True)
    >>> target = torch.randint(2, (1, C, 5))
    >>> kwargs = {"alpha": 0.25, "gamma": 2.0, "reduction": 'mean'}
    >>> output = binary_focal_loss_with_logits(pred, target, **kwargs)
    >>> output.backward()

r   r   r   r   r   Nr   r   r   r   z(pos_weight must be torch.Tensor or None.r   z-pos_weight shape must be (num_of_classes,): (r   z5pos_weight and pred must be in the same device. Got: r   r   r   r   r    r!   r"   )r   r   r#   r   r   
functional
logsigmoidr	   r(   r'   r)   r   r,   r+   r&   r    r!   r-   )r.   r/   r0   r1   r2   
pos_weightr3   r4   log_probs_poslog_probs_negr6   pos_termneg_termr:   r;   r9   r=   s                    r>   binary_focal_loss_with_logitsrl      s   b t_-v||+/DTZZLPVW]WcWcVd-efv}}$
;DKK=fmm_]
 #%--":":4"@M"$--":":D5"AM,VBF%3%3+//155e<<vEUH+//155e<<fMP]]H#%K8+ZZ]NTQC#djjn"555Nz+UVa N2[z7G7G7I^7[;N;K8T^TdTdSef	
 	,CJDUDUCVV[\`\g\g[hi	

  __^4
(%0Hv'MN\\!_.S6<<>^3S77GxPVP\P\~^	
 	MMT[[(?eTXT_T_S`a	

 ^,$F K 
f	zz(#
 K	 
e	yy" K "$<YK"HIIr@   c                  b   ^  \ rS rSrSr     S             SU 4S jjjrSS jrSrU =r$ )	BinaryFocalLossWithLogitsi8  a  Criterion that computes Focal loss.

According to :cite:`lin2018focal`, the Focal loss is computed as follows:

.. math::

    \text{FL}(p_t) = -\alpha_t (1 - p_t)^{\gamma} \, \text{log}(p_t)

torch.where:
   - :math:`p_t` is the model's estimated probability for each class.

Args:
    alpha: Weighting factor :math:`\alpha \in [0, 1]`.
    gamma: Focusing parameter :math:`\gamma >= 0`.
    reduction: 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.
    pos_weight: a weight of positive examples with shape :math:`(num\_of\_classes,)`.
      It is possible to trade off recall and precision by adding weights to positive examples.
    weight: weights for classes with shape :math:`(num\_of\_classes,)`.
    ignore_index: labels with this value are ignored in the loss computation.

Shape:
    - Pred: :math:`(N, C, *)` where C = number of classes.
    - Target: the same shape as Pred :math:`(N, C, *)`
      where each value is between 0 and 1.

Examples:
    >>> C = 3  # num_classes
    >>> pred = torch.randn(1, C, 5, requires_grad=True)
    >>> target = torch.randint(2, (1, C, 5))
    >>> kwargs = {"alpha": 0.25, "gamma": 2.0, "reduction": 'mean'}
    >>> criterion = BinaryFocalLossWithLogits(**kwargs)
    >>> output = criterion(pred, target)
    >>> output.backward()

c                j   > [         TU ]  5         Xl        X l        X0l        X@l        XPl        X`l        g rE   )rF   rG   r0   r1   r2   rg   r3   r4   )rH   r0   r1   r2   rg   r3   r4   rI   s          r>   rG   "BinaryFocalLossWithLogits.__init__a  s/     	&+
!
'2<.4+7r@   c           
         [        XU R                  U R                  U R                  U R                  U R
                  U R                  5      $ rE   )rl   r0   r1   r2   rg   r3   r4   rL   s      r>   rM   !BinaryFocalLossWithLogits.forwardr  s<    ,$**djj$..$//SWS^S^`d`q`q
 	
r@   )r0   r1   r4   rg   r2   r3   )rP   r   NNrQ   )r0   rR   r1   rS   r2   rT   rg   rU   r3   rU   r4   rV   rW   rX   rY   r[   rc   s   @r>   rn   rn   8  sr    &V -1)-&*88 8 	8
 +8 '8 $8 
8 8"
 
r@   rn   rO   )r.   rZ   r/   rZ   r0   rR   r1   rS   r2   rT   r3   rU   r4   rV   rW   rZ   )g      ?rP   r   NNrQ   )r.   rZ   r/   rZ   r0   rR   r1   rS   r2   rT   rg   rU   r3   rU   r4   rV   rW   rZ   )
__future__r   typingr   r&   r   kornia.core.checkr   r   r   kornia.losses._utilsr	   kornia.losses.one_hotr
   r?   ModulerB   rl   rn    r@   r>   <module>rz      s%  $ #    V V 3 ) %)"&h
hh h 	h
 h #h  h hV7p		 7pz ")-%)"&o
oo o 	o
 o 'o #o  o od=
		 =
r@   