Ë
    ýÿæi•5  ã                   óî   — d dl mZ d dl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 d dl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y)é    )ÚSequence)ÚAnyÚOptionalÚUnion)ÚTensor)ÚLiteral)Ú_ClassificationTaskWrapper)ÚBinaryConfusionMatrixÚMulticlassConfusionMatrix)Ú"_binary_cohen_kappa_arg_validationÚ_cohen_kappa_reduceÚ&_multiclass_cohen_kappa_arg_validation)ÚMetric)ÚClassificationTaskNoMultilabel)Ú_MATPLOTLIB_AVAILABLE)Ú_AX_TYPEÚ_PLOT_OUT_TYPEzBinaryCohenKappa.plotzMulticlassCohenKappa.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
<   	 	 	 	 dde
dee   deed      dededdfˆ 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 )ÚBinaryCohenKappaa´	  Calculate `Cohen's kappa score`_ that measures inter-annotator agreement for binary tasks.

    .. math::
        \kappa = (p_o - p_e) / (1 - p_e)

    where :math:`p_o` is the empirical probability of agreement and :math:`p_e` is
    the expected agreement when both annotators assign labels randomly. Note that
    :math:`p_e` is estimated using a per-annotator empirical prior over the
    class labels.

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

    - ``preds`` (:class:`~torch.Tensor`): A int or float tensor of shape ``(N, ...)``. If preds is a floating point
      tensor with values outside [0,1] range we consider the input to be logits and will auto apply sigmoid per element.
      Additionally, we convert to int tensor with thresholding using the value in ``threshold``.
    - ``target`` (:class:`~torch.Tensor`): An int tensor of shape ``(N, ...)``.

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

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

    - ``bc_kappa`` (:class:`~torch.Tensor`): A tensor containing cohen kappa score

    Args:
        threshold: Threshold for transforming probability to binary (0,1) predictions
        ignore_index:
            Specifies a target value that is ignored and does not contribute to the metric calculation
        weights: Weighting type to calculate the score. Choose from:

            - ``None`` or ``'none'``: no weighting
            - ``'linear'``: linear weighting
            - ``'quadratic'``: quadratic weighting

        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 (preds is int tensor):
        >>> from torch import tensor
        >>> from torchmetrics.classification import BinaryCohenKappa
        >>> target = tensor([1, 1, 0, 0])
        >>> preds = tensor([0, 1, 0, 0])
        >>> metric = BinaryCohenKappa()
        >>> metric(preds, target)
        tensor(0.5000)

    Example (preds is float tensor):
        >>> from torchmetrics.classification import BinaryCohenKappa
        >>> target = tensor([1, 1, 0, 0])
        >>> preds = tensor([0.35, 0.85, 0.48, 0.01])
        >>> metric = BinaryCohenKappa()
        >>> metric(preds, target)
        tensor(0.5000)

    FÚis_differentiableTÚhigher_is_betterÚfull_state_updateç        Úplot_lower_boundç      ð?Úplot_upper_boundNÚ	thresholdÚignore_indexÚweights©ÚlinearÚ	quadraticÚnoneÚvalidate_argsÚkwargsÚreturnc                 óh   •— t        ‰| �  ||fd ddœ|¤Ž |rt        |||«       || _        || _        y ©NF)Ú	normalizer$   )ÚsuperÚ__init__r   r   r$   )Úselfr   r   r   r$   r%   Ú	__class__s         €ú|/Volumes/fast/ai/experiments/voice-extract-mac/.venv/lib/python3.12/site-packages/torchmetrics/classification/cohen_kappa.pyr+   zBinaryCohenKappa.__init__d   s@   ø€ ô 	‰Ñ˜ LÐ`¸DÐPUÑ`ÐY_Ò`ÙÜ.¨y¸,ÈÔPØˆŒØ*ˆÕó    c                 óB   — t        | j                  | j                  «      S ©zCompute metric.©r   Úconfmatr   ©r,   s    r.   ÚcomputezBinaryCohenKappa.computer   ó   € ä" 4§<¡<°·±Ó>Ð>r/   ÚvalÚaxc                 ó&   — | j                  ||«      S )a9  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

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

        .. plot::
            :scale: 75

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

        ©Ú_plot©r,   r7   r8   s      r.   ÚplotzBinaryCohenKappa.plotv   ó   € ðP �z‰z˜#˜rÓ"Ð"r/   )ç      à?NNT©NN)Ú__name__Ú
__module__Ú__qualname__Ú__doc__r   ÚboolÚ__annotations__r   r   r   Úfloatr   r   Úintr   r   r+   r   r5   r   r   r   r   r=   Ú__classcell__©r-   s   @r.   r   r   $   sè   ø… ñ7ðr $Ð�tÓ#Ø!Ð�dÓ!Ø#Ð�tÓ#Ø!Ð�eÓ!Ø!Ð�eÓ!ð Ø&*ØDHØ"ñ+àð+ð ˜s‘mð+ð ˜'Ð"?Ñ@ÑAð	+ð
 ð+ð ð+ð 
õ+ð?˜ó ?ð
 _cñ(#Ø˜E &¨(°6Ñ*:Ð":Ñ;Ñ<ð(#ØIQÐRZÑI[ð(#à	÷(#r/   r   c                   óì   ‡ — 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<   	 	 	 ddedee   deed      dededdfˆ 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 )ÚMulticlassCohenKappaa"
  Calculate `Cohen's kappa score`_ that measures inter-annotator agreement for multiclass tasks.

    .. math::
        \kappa = (p_o - p_e) / (1 - p_e)

    where :math:`p_o` is the empirical probability of agreement and :math:`p_e` is
    the expected agreement when both annotators assign labels randomly. Note that
    :math:`p_e` is estimated using a per-annotator empirical prior over the
    class labels.

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

    - ``preds`` (:class:`~torch.Tensor`): Either an int tensor of shape ``(N, ...)` or float tensor of shape
      ``(N, C, ..)``. If preds is a floating point we apply ``torch.argmax`` along the ``C`` dimension to automatically
      convert probabilities/logits into an int tensor.
    - ``target`` (:class:`~torch.Tensor`): An int tensor of shape ``(N, ...)``.

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

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

    - ``mcck`` (:class:`~torch.Tensor`): A tensor containing cohen kappa score

    Args:
        num_classes: Integer specifying the number of classes
        ignore_index:
            Specifies a target value that is ignored and does not contribute to the metric calculation
        weights: Weighting type to calculate the score. Choose from:

            - ``None`` or ``'none'``: no weighting
            - ``'linear'``: linear weighting
            - ``'quadratic'``: quadratic weighting

        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 (pred is integer tensor):
        >>> from torch import tensor
        >>> from torchmetrics.classification import MulticlassCohenKappa
        >>> target = tensor([2, 1, 0, 0])
        >>> preds = tensor([2, 1, 0, 1])
        >>> metric = MulticlassCohenKappa(num_classes=3)
        >>> metric(preds, target)
        tensor(0.6364)

    Example (pred is float tensor):
        >>> from torchmetrics.classification import MulticlassCohenKappa
        >>> target = tensor([2, 1, 0, 0])
        >>> preds = tensor([[0.16, 0.26, 0.58],
        ...                 [0.22, 0.61, 0.17],
        ...                 [0.71, 0.09, 0.20],
        ...                 [0.05, 0.82, 0.13]])
        >>> metric = MulticlassCohenKappa(num_classes=3)
        >>> metric(preds, target)
        tensor(0.6364)

    Fr   Tr   r   r   r   r   r   ÚClassÚplot_legend_nameNÚnum_classesr   r   r    r$   r%   r&   c                 óh   •— t        ‰| �  ||fd ddœ|¤Ž |rt        |||«       || _        || _        y r(   )r*   r+   r   r   r$   )r,   rO   r   r   r$   r%   r-   s         €r.   r+   zMulticlassCohenKappa.__init__å   s@   ø€ ô 	‰Ñ˜ lÐb¸dÐRWÑbÐ[aÒbÙÜ2°;ÀÈgÔVØˆŒØ*ˆÕr/   c                 óB   — t        | j                  | j                  «      S r1   r2   r4   s    r.   r5   zMulticlassCohenKappa.computeó   r6   r/   r7   r8   c                 ó&   — | j                  ||«      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

            >>> from torch import randn, randint
            >>> # Example plotting a single value
            >>> from torchmetrics.classification import MulticlassCohenKappa
            >>> metric = MulticlassCohenKappa(num_classes=3)
            >>> metric.update(randn(20,3).softmax(dim=-1), randint(3, (20,)))
            >>> fig_, ax_ = metric.plot()

        .. plot::
            :scale: 75

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

        r:   r<   s      r.   r=   zMulticlassCohenKappa.plot÷   r>   r/   )NNTr@   )rA   rB   rC   rD   r   rE   rF   r   r   r   rG   r   rN   ÚstrrH   r   r   r   r+   r   r5   r   r   r   r   r=   rI   rJ   s   @r.   rL   rL   ¡   sð   ø… ñ:ðx $Ð�tÓ#Ø!Ð�dÓ!Ø#Ð�tÓ#Ø!Ð�eÓ!Ø!Ð�eÓ!Ø#Ð�cÓ#ð
 '+ØDHØ"ñ+àð+ð ˜s‘mð+ð ˜'Ð"?Ñ@ÑAð	+ð
 ð+ð ð+ð 
õ+ð?˜ó ?ð
 _cñ(#Ø˜E &¨(°6Ñ*:Ð":Ñ;Ñ<ð(#ØIQÐRZÑI[ð(#à	÷(#r/   rL   c                   ól   — e Zd ZdZ	 	 	 	 	 dded    ded   dedee   deed	      d
ee   de	de
defd„Zy)Ú
CohenKappaa0  Calculate `Cohen's kappa score`_ that measures inter-annotator agreement.

    .. math::
        \kappa = (p_o - p_e) / (1 - p_e)

    where :math:`p_o` is the empirical probability of agreement and :math:`p_e` is
    the expected agreement when both annotators assign labels randomly. Note that
    :math:`p_e` is estimated using a per-annotator empirical prior over the
    class labels.

    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.BinaryCohenKappa` and
    :class:`~torchmetrics.classification.MulticlassCohenKappa` for the specific details of each argument influence and
    examples.

    Legacy Example:
        >>> from torch import tensor
        >>> target = tensor([1, 1, 0, 0])
        >>> preds = tensor([0, 1, 0, 0])
        >>> cohenkappa = CohenKappa(task="multiclass", num_classes=2)
        >>> cohenkappa(preds, target)
        tensor(0.5000)

    NÚclsÚtask)ÚbinaryÚ
multiclassr   rO   r   r    r   r$   r%   r&   c                 ó@  — t        j                  |«      }|j                  |||dœ«       |t         j                  k(  rt	        |fi |¤ŽS |t         j
                  k(  r4t        |t        «      st        dt        |«      › d�«      ‚t        |fi |¤ŽS t        d|› d�«      ‚)zInitialize task metric.)r   r   r$   z+`num_classes` is expected to be `int` but `z was passed.`zTask z not supported!)r   Úfrom_strÚupdateÚBINARYr   Ú
MULTICLASSÚ
isinstancerH   Ú
ValueErrorÚtyperL   )rV   rW   r   rO   r   r   r$   r%   s           r.   Ú__new__zCohenKappa.__new__=  s¡   € ô .×6Ñ6°tÓ<ˆØ�‰ '¸<ÐZgÑhÔiØÔ1×8Ñ8Ò8Ü# IÑ8°Ñ8Ð8ØÔ1×<Ñ<Ò<Ü˜k¬3Ô/Ü Ð#NÌtÐT_ÓO`ÐNaÐanÐ!oÓpÐpÜ'¨Ñ>°vÑ>Ð>Ü˜5   oÐ6Ó7Ð7r/   )r?   NNNT)rA   rB   rC   rD   ra   r   rG   r   rH   rE   r   r   rb   © r/   r.   rU   rU   "  s‘   „ ñð: Ø%)ØDHØ&*Ø"ñ8Ø�,Ñð8àÐ,Ñ-ð8ð ð8ð ˜c‘]ð	8ð
 ˜'Ð"?Ñ@ÑAð8ð ˜s‘mð8ð ð8ð ð8ð 
ô8r/   rU   N) Úcollections.abcr   Útypingr   r   r   Útorchr   Útyping_extensionsr   Ú torchmetrics.classification.baser	   Ú,torchmetrics.classification.confusion_matrixr
   r   Ú2torchmetrics.functional.classification.cohen_kappar   r   r   Útorchmetrics.metricr   Útorchmetrics.utilities.enumsr   Útorchmetrics.utilities.importsr   Útorchmetrics.utilities.plotr   r   Ú__doctest_skip__r   rL   rU   rc   r/   r.   Ú<module>rp      sp   ðõ %ß 'Ñ 'å Ý %å Gß i÷ñ õ
 'Ý GÝ @ß @áØ/Ð1LÐMÐôz#Ð,ô z#ôz~#Ð4ô ~#ôB.8Ð+õ .8r/   