§
    ’©ºjÔ=  ã                   ó  — d dl mZ d dlmZmZmZ d dlZd dlmZ d dlm	Z	 d dl
mZ d dlmZmZmZmZmZmZmZmZmZ d dlmZ d d	lmZ d d
lmZ d dlmZmZ esddgZ G d„ de¦  «        Z  G d„ de¦  «        Z! G d„ de¦  «        Z"dS )é    )ÚSequence)ÚAnyÚOptionalÚUnionN)ÚTensor)ÚLiteral)Ú_ClassificationTaskWrapper)	Ú_binary_confusion_matrix_formatÚ!_binary_hinge_loss_arg_validationÚ$_binary_hinge_loss_tensor_validationÚ_binary_hinge_loss_updateÚ_hinge_loss_computeÚ#_multiclass_confusion_matrix_formatÚ%_multiclass_hinge_loss_arg_validationÚ(_multiclass_hinge_loss_tensor_validationÚ_multiclass_hinge_loss_update)ÚMetric)ÚClassificationTaskNoMultilabel)Ú_MATPLOTLIB_AVAILABLE)Ú_AX_TYPEÚ_PLOT_OUT_TYPEzBinaryHingeLoss.plotzMulticlassHingeLoss.plotc                   ó  ‡ — e Zd ZU dZdZeed<   dZeed<   dZeed<   dZ	e
ed<   d	Ze
ed
<   eed<   eed<   	 	 	 ddedee         dededdf
ˆ fd„Zdededdfd„Zdefd„Z	 ddeeeee         f                  dee         defd„Zˆ xZS )ÚBinaryHingeLossa'  Compute the mean `Hinge loss`_ typically used for Support Vector Machines (SVMs) for binary tasks.

    .. math::
        \text{Hinge loss} = \max(0, 1 - y \times \hat{y})

    Where :math:`y \in {-1, 1}` is the target, and :math:`\hat{y} \in \mathbb{R}` is the prediction.

    As input to ``forward`` and ``update`` the metric accepts the following input:

    - ``preds`` (:class:`~torch.Tensor`): A float tensor of shape ``(N, ...)``. Preds should be a tensor containing
      probabilities or logits for each observation. If preds has values outside [0,1] range we consider the input
      to be logits and will auto apply sigmoid per element.
    - ``target`` (:class:`~torch.Tensor`): An int tensor of shape ``(N, ...)``. Target should be a tensor containing
      ground truth labels, and therefore only contain {0,1} values (except if `ignore_index` is specified). The value
      1 always encodes the positive class.

    .. tip::
       Additional dimension ``...`` will be flattened into the batch dimension.

    As output to ``forward`` and ``compute`` the metric returns the following output:

    - ``bhl`` (:class:`~torch.Tensor`): A tensor containing the hinge loss.

    Args:
        squared:
            If True, this will compute the squared hinge loss. Otherwise, computes the regular hinge loss.
        ignore_index:
            Specifies a target value that is ignored and does not contribute to the metric calculation
        validate_args: bool indicating if input arguments and tensors should be validated for correctness.
            Set to ``False`` for faster computations.
        kwargs: Additional keyword arguments, see :ref:`Metric kwargs` for more info.

    Example:
        >>> from torchmetrics.classification import BinaryHingeLoss
        >>> preds = torch.tensor([0.25, 0.25, 0.55, 0.75, 0.75])
        >>> target = torch.tensor([0, 0, 1, 1, 1])
        >>> bhl = BinaryHingeLoss()
        >>> bhl(preds, target)
        tensor(0.6900)
        >>> bhl = BinaryHingeLoss(squared=True)
        >>> bhl(preds, target)
        tensor(0.6905)

    TÚis_differentiableFÚhigher_is_betterÚfull_state_updateç        Úplot_lower_boundç      ð?Úplot_upper_boundÚmeasuresÚtotalNÚsquaredÚignore_indexÚvalidate_argsÚkwargsÚreturnc                 ó0  •—  t          ¦   «         j        di |¤Ž |rt          ||¦  «         || _        || _        || _        |                      dt          j        d¦  «        d¬¦  «         |                      dt          j        d¦  «        d¬¦  «         d S )Nr!   r   Úsum©ÚdefaultÚdist_reduce_fxr"   r   © )	ÚsuperÚ__init__r   r%   r#   r$   Ú	add_stateÚtorchÚtensor)Úselfr#   r$   r%   r&   Ú	__class__s        €úq/root/private/project/pallet_detection_v2/.venv/lib/python3.11/site-packages/torchmetrics/classification/hinge.pyr/   zBinaryHingeLoss.__init__a   sš   ø€ ð 	�‰ŒÔÐ"Ð"˜6Ð"Ð"Ð"Øð 	EÝ-¨g°|ÑDÔDÐDØ*ˆÔØˆŒØ(ˆÔà�Š�z­5¬<¸Ñ+<Ô+<ÈUˆÑSÔSÐSØ�Š�w­¬°Q©¬ÈˆÑNÔNÐNÐNÐNó    ÚpredsÚtargetc                 óê   — | j         rt          ||| j        ¦  «         t          ||d| j        d¬¦  «        \  }}t	          ||| j        ¦  «        \  }}| xj        |z  c_        | xj        |z  c_        dS )úUpdate metric state.r   F)Ú	thresholdr$   Úconvert_to_labelsN)r%   r   r$   r
   r   r#   r!   r"   ©r3   r7   r8   r!   r"   s        r5   ÚupdatezBinaryHingeLoss.updater   s‡   € àÔð 	SÝ0°¸ÀÔ@QÑRÔRÐRÝ7Ø�6 S°tÔ7HÐ\að
ñ 
ô 
‰ˆˆvõ 4°E¸6À4Ä<ÑPÔP‰ˆ�%ØˆŒ˜Ñ!ˆŒØˆ
Œ
�eÑˆ
Œ
ˆ
ˆ
r6   c                 ó6   — t          | j        | j        ¦  «        S ©zCompute metric.©r   r!   r"   ©r3   s    r5   ÚcomputezBinaryHingeLoss.compute}   ó   € å" 4¤=°$´*Ñ=Ô=Ð=r6   ÚvalÚaxc                 ó.   — |                       ||¦  «        S )a5  Plot a single or multiple values from the metric.

        Args:
            val: Either a single result from calling `metric.forward` or `metric.compute` or a list of these results.
                If no value is provided, will automatically call `metric.compute` and plot that result.
            ax: An matplotlib axis object. If provided will add plot to that axis

        Returns:
            Figure object and Axes object

        Raises:
            ModuleNotFoundError:
                If `matplotlib` is not installed

        .. plot::
            :scale: 75

            >>> # Example plotting a single value
            >>> from torch import rand, randint
            >>> from torchmetrics.classification import BinaryHingeLoss
            >>> metric = BinaryHingeLoss()
            >>> metric.update(rand(10), randint(2,(10,)))
            >>> fig_, ax_ = metric.plot()

        .. plot::
            :scale: 75

            >>> # Example plotting multiple values
            >>> from torch import rand, randint
            >>> from torchmetrics.classification import BinaryHingeLoss
            >>> metric = BinaryHingeLoss()
            >>> values = [ ]
            >>> for _ in range(10):
            ...     values.append(metric(rand(10), randint(2,(10,))))
            >>> fig_, ax_ = metric.plot(values)

        ©Ú_plot©r3   rE   rF   s      r5   ÚplotzBinaryHingeLoss.plot�   ó   € ðP �zŠz˜#˜rÑ"Ô"Ð"r6   )FNT©NN)Ú__name__Ú
__module__Ú__qualname__Ú__doc__r   ÚboolÚ__annotations__r   r   r   Úfloatr    r   r   Úintr   r/   r>   rC   r   r   r   r   rK   Ú__classcell__©r4   s   @r5   r   r   *   sœ  ø€ € € € € € ð+ð +ðZ #Ð�tÐ"Ð"Ñ"Ø"Ð�dÐ"Ð"Ñ"Ø#Ð�tÐ#Ð#Ñ#Ø!Ð�eÐ!Ð!Ñ!Ø!Ð�eÐ!Ð!Ñ!àÐÐÑØ€M€M�Mð Ø&*Ø"ð	Oð OàðOð ˜s”mðOð ð	Oð
 ðOð 
ðOð Oð Oð Oð Oð Oð"	˜Fð 	¨Fð 	°tð 	ð 	ð 	ð 	ð>˜ð >ð >ð >ð >ð
 _cð(#ð (#Ø˜E &¨(°6Ô*:Ð":Ô;Ô<ð(#ØIQÐRZÔI[ð(#à	ð(#ð (#ð (#ð (#ð (#ð (#ð (#ð (#r6   r   c                   ó8  ‡ — e Zd ZU dZdZeed<   dZeed<   dZeed<   dZ	e
ed<   d	Ze
ed
<   dZeed<   eed<   eed<   	 	 	 	 d!dededed         dee         dededdfˆ fd„Zdededdfd„Zdefd„Z	 d"deeeee         f                  dee         defd „Zˆ xZS )#ÚMulticlassHingeLossaˆ  Compute the mean `Hinge loss`_ typically used for Support Vector Machines (SVMs) for multiclass tasks.

    The metric can be computed in two ways. Either, the definition by Crammer and Singer is used:

    .. math::
        \text{Hinge loss} = \max\left(0, 1 - \hat{y}_y + \max_{i \ne y} (\hat{y}_i)\right)

    Where :math:`y \in {0, ..., \mathrm{C}}` is the target class (where :math:`\mathrm{C}` is the number of classes),
    and :math:`\hat{y} \in \mathbb{R}^\mathrm{C}` is the predicted output per class. Alternatively, the metric can
    also be computed in one-vs-all approach, where each class is valued against all other classes in a binary fashion.

    As input to ``forward`` and ``update`` the metric accepts the following input:

    - ``preds`` (:class:`~torch.Tensor`): A float tensor of shape ``(N, C, ...)``. Preds should be a tensor
      containing probabilities or logits for each observation. If preds has values outside [0,1] range we consider
      the input to be logits and will auto apply softmax per sample.
    - ``target`` (:class:`~torch.Tensor`): An int tensor of shape ``(N, ...)``. Target should be a tensor containing
      ground truth labels, and therefore only contain values in the [0, n_classes-1] range (except if `ignore_index`
      is specified).

    .. tip::
       Additional dimension ``...`` will be flattened into the batch dimension.

    As output to ``forward`` and ``compute`` the metric returns the following output:

    - ``mchl`` (:class:`~torch.Tensor`): A tensor containing the multi-class hinge loss.

    Args:
        num_classes: Integer specifying the number of classes
        squared:
            If True, this will compute the squared hinge loss. Otherwise, computes the regular hinge loss.
        multiclass_mode:
            Determines how to compute the metric
        ignore_index:
            Specifies a target value that is ignored and does not contribute to the metric calculation
        validate_args: bool indicating if input arguments and tensors should be validated for correctness.
            Set to ``False`` for faster computations.
        kwargs: Additional keyword arguments, see :ref:`Metric kwargs` for more info.

    Example:
        >>> from torchmetrics.classification import MulticlassHingeLoss
        >>> preds = torch.tensor([[0.25, 0.20, 0.55],
        ...                       [0.55, 0.05, 0.40],
        ...                       [0.10, 0.30, 0.60],
        ...                       [0.90, 0.05, 0.05]])
        >>> target = torch.tensor([0, 1, 2, 0])
        >>> mchl = MulticlassHingeLoss(num_classes=3)
        >>> mchl(preds, target)
        tensor(0.9125)
        >>> mchl = MulticlassHingeLoss(num_classes=3, squared=True)
        >>> mchl(preds, target)
        tensor(1.1131)
        >>> mchl = MulticlassHingeLoss(num_classes=3, multiclass_mode='one-vs-all')
        >>> mchl(preds, target)
        tensor([0.8750, 1.1250, 1.1000])

    Tr   Fr   r   r   r   r   r    ÚClassÚplot_legend_namer!   r"   úcrammer-singerNÚnum_classesr#   Úmulticlass_mode©r\   z
one-vs-allr$   r%   r&   r'   c                 óŽ  •—  t          ¦   «         j        di |¤Ž |rt          ||||¦  «         || _        || _        || _        || _        || _        |                      d| j        dk    rt          j
        d¦  «        nt          j        |¦  «        d¬¦  «         |                      dt          j
        d¦  «        d¬¦  «         d S )	Nr!   r\   r   r)   r*   r"   r   r-   )r.   r/   r   r%   r]   r#   r^   r$   r0   r1   r2   Úzeros)r3   r]   r#   r^   r$   r%   r&   r4   s          €r5   r/   zMulticlassHingeLoss.__init__ñ   så   ø€ ð 	�‰ŒÔÐ"Ð"˜6Ð"Ð"Ð"Øð 	gÝ1°+¸wÈÐYeÑfÔfÐfØ*ˆÔØ&ˆÔØˆŒØ.ˆÔØ(ˆÔà�ŠØàÔ#Ð'7Ò7Ð7õ ”L Ñ%Ô%Ð%å”Øñô ð !ð 	ñ 	
ô 	
ð 	
ð 	�Š�w­¬°Q©¬ÈˆÑNÔNÐNÐNÐNr6   r7   r8   c                 ó   — | j         rt          ||| j        | j        ¦  «         t	          ||| j        d¬¦  «        \  }}t          ||| j        | j        ¦  «        \  }}| xj        |z  c_        | xj	        |z  c_	        dS )r:   F)r<   N)
r%   r   r]   r$   r   r   r#   r^   r!   r"   r=   s        r5   r>   zMulticlassHingeLoss.update  sˆ   € àÔð 	iÝ4°U¸FÀDÔDTÐVZÔVgÑhÔhÐhÝ;¸EÀ6È4ÔK\ÐpuÐvÑvÔv‰ˆˆvÝ7¸¸vÀtÄ|ÐUYÔUiÑjÔj‰ˆ�%ØˆŒ˜Ñ!ˆŒØˆ
Œ
�eÑˆ
Œ
ˆ
ˆ
r6   c                 ó6   — t          | j        | j        ¦  «        S r@   rA   rB   s    r5   rC   zMulticlassHingeLoss.compute  rD   r6   rE   rF   c                 ó.   — |                       ||¦  «        S )a€  Plot a single or multiple values from the metric.

        Args:
            val: Either a single result from calling `metric.forward` or `metric.compute` or a list of these results.
                If no value is provided, will automatically call `metric.compute` and plot that result.
            ax: An matplotlib axis object. If provided will add plot to that axis

        Returns:
            Figure object and Axes object

        Raises:
            ModuleNotFoundError:
                If `matplotlib` is not installed

        .. plot::
            :scale: 75

            >>> # Example plotting a single value per class
            >>> from torch import randint, randn
            >>> from torchmetrics.classification import MulticlassHingeLoss
            >>> metric = MulticlassHingeLoss(num_classes=3)
            >>> metric.update(randn(20, 3), randint(3, (20,)))
            >>> fig_, ax_ = metric.plot()

        .. plot::
            :scale: 75

            >>> # Example plotting a multiple values per class
            >>> from torch import randint, randn
            >>> from torchmetrics.classification import MulticlassHingeLoss
            >>> metric = MulticlassHingeLoss(num_classes=3)
            >>> values = []
            >>> for _ in range(20):
            ...     values.append(metric(randn(20, 3), randint(3, (20,))))
            >>> fig_, ax_ = metric.plot(values)

        rH   rJ   s      r5   rK   zMulticlassHingeLoss.plot  rL   r6   )Fr\   NTrM   )rN   rO   rP   rQ   r   rR   rS   r   r   r   rT   r    r[   Ústrr   rU   r   r   r   r/   r>   rC   r   r   r   r   rK   rV   rW   s   @r5   rY   rY   ¬   sÌ  ø€ € € € € € ð8ð 8ðt #Ð�tÐ"Ð"Ñ"Ø"Ð�dÐ"Ð"Ñ"Ø#Ð�tÐ#Ð#Ñ#Ø!Ð�eÐ!Ð!Ñ!Ø!Ð�eÐ!Ð!Ñ!Ø#Ð�cÐ#Ð#Ñ#àÐÐÑØ€M€M�Mð
 ØCSØ&*Ø"ðOð OàðOð ðOð !Ð!?Ô@ð	Oð
 ˜s”mðOð ðOð ðOð 
ðOð Oð Oð Oð Oð Oð:˜Fð ¨Fð °tð ð ð ð ð>˜ð >ð >ð >ð >ð
 _cð(#ð (#Ø˜E &¨(°6Ô*:Ð":Ô;Ô<ð(#ØIQÐRZÔI[ð(#à	ð(#ð (#ð (#ð (#ð (#ð (#ð (#ð (#r6   rY   c                   ó’   — e Zd ZdZ	 	 	 	 	 dded          ded         d	ee         d
edeed                  dee         dede	de
fd„ZdS )Ú	HingeLossaî  Compute the mean `Hinge loss`_ typically used for Support Vector Machines (SVMs).

    This function is a simple wrapper to get the task specific versions of this metric, which is done by setting the
    ``task`` argument to either ``'binary'`` or ``'multiclass'``. See the documentation of
    :class:`~torchmetrics.classification.BinaryHingeLoss` and :class:`~torchmetrics.classification.MulticlassHingeLoss`
    for the specific details of each argument influence and examples.

    Legacy Example:
        >>> from torch import tensor
        >>> target = tensor([0, 1, 1])
        >>> preds = tensor([0.5, 0.7, 0.1])
        >>> hinge = HingeLoss(task="binary")
        >>> hinge(preds, target)
        tensor(0.9000)

        >>> target = tensor([0, 1, 2])
        >>> preds = tensor([[-1.0, 0.9, 0.2], [0.5, -1.1, 0.8], [2.2, -0.5, 0.3]])
        >>> hinge = HingeLoss(task="multiclass", num_classes=3)
        >>> hinge(preds, target)
        tensor(1.5551)

        >>> target = tensor([0, 1, 2])
        >>> preds = tensor([[-1.0, 0.9, 0.2], [0.5, -1.1, 0.8], [2.2, -0.5, 0.3]])
        >>> hinge = HingeLoss(task="multiclass", num_classes=3, multiclass_mode="one-vs-all")
        >>> hinge(preds, target)
        tensor([1.3743, 1.1945, 1.2359])

    NFr\   TÚclsÚtask)ÚbinaryÚ
multiclassr]   r#   r^   r_   r$   r%   r&   r'   c                 ó�  — t          j        |¦  «        }|                     ||dœ¦  «         |t           j        k    rt	          |fi |¤ŽS |t           j        k    r[t          |t          ¦  «        s t          dt          |¦  «        › d�¦  «        ‚|dvrt          d|› d�¦  «        ‚t          |||fi |¤ŽS t          d|› d�¦  «        ‚)	zInitialize task metric.)r$   r%   z+`num_classes` is expected to be `int` but `z was passed.`r_   zQ`multiclass_mode` is expected to be one of 'crammer-singer' or 'one-vs-all' but `z` was passed.zUnsupported task `ú`)r   Úfrom_strr>   ÚBINARYr   Ú
MULTICLASSÚ
isinstancerU   Ú
ValueErrorÚtyperY   )rh   ri   r]   r#   r^   r$   r%   r&   s           r5   Ú__new__zHingeLoss.__new__d  s  € õ .Ô6°tÑ<Ô<ˆØ�Š |ÀmÐTÐTÑUÔUÐUØÕ1Ô8Ò8Ð8Ý" 7Ð5Ð5¨fÐ5Ð5Ð5ØÕ1Ô<Ò<Ð<Ý˜k­3Ñ/Ô/ð qÝ Ð!oÍtÐT_ÑO`ÔO`Ð!oÐ!oÐ!oÑpÔpÐpØÐ&FÐFÐFÝ ð7Ø'ð7ð 7ð 7ñô ð õ ' {°G¸_ÐWÐWÐPVÐWÐWÐWÝÐ5¨dÐ5Ð5Ð5Ñ6Ô6Ð6r6   )NFr\   NT)rN   rO   rP   rQ   rs   r   r   rU   rR   r   r   rt   r-   r6   r5   rg   rg   F  s½   € € € € € ðð ð@ &*ØØM]Ø&*Ø"ð7ð 7Ø�+Ôð7àÐ,Ô-ð7ð ˜c”]ð7ð ð	7ð
 " 'Ð*HÔ"IÔJð7ð ˜s”mð7ð ð7ð ð7ð 
ð7ð 7ð 7ð 7ð 7ð 7r6   rg   )#Úcollections.abcr   Útypingr   r   r   r1   r   Útyping_extensionsr   Ú torchmetrics.classification.baser	   Ú,torchmetrics.functional.classification.hinger
   r   r   r   r   r   r   r   r   Útorchmetrics.metricr   Útorchmetrics.utilities.enumsr   Útorchmetrics.utilities.importsr   Útorchmetrics.utilities.plotr   r   Ú__doctest_skip__r   rY   rg   r-   r6   r5   ú<module>r      sä  ðð %Ð $Ð $Ð $Ð $Ð $Ø 'Ð 'Ð 'Ð 'Ð 'Ð 'Ð 'Ð 'Ð 'Ð 'à €€€Ø Ð Ð Ð Ð Ð Ø %Ð %Ð %Ð %Ð %Ð %à GÐ GÐ GÐ GÐ GÐ Gð
ð 
ð 
ð 
ð 
ð 
ð 
ð 
ð 
ð 
ð 
ð 
ð 
ð 
ð 
ð 
ð 
ð 
ð 
ð 
ð 
ð 
ð 'Ð &Ð &Ð &Ð &Ð &Ø GÐ GÐ GÐ GÐ GÐ GØ @Ð @Ð @Ð @Ð @Ð @Ø @Ð @Ð @Ð @Ð @Ð @Ð @Ð @àð LØ.Ð0JÐKÐð#ð #ð #ð #ð #�fñ #ô #ð #ðDW#ð W#ð W#ð W#ð W#˜&ñ W#ô W#ð W#ðt67ð 67ð 67ð 67ð 67Ð*ñ 67ô 67ð 67ð 67ð 67r6   