a
    d_5                     @   s   d dl 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 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sddgZG dd deZG dd deZG dd de
ZdS )    )AnyOptionalSequence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_TYPEBinaryCohenKappa.plotMulticlassCohenKappa.plotc                       s   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e
ee eed  eedd fddZedddZdeeeee f  ee edddZ  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.
      Addtionally, we convert to int tensor with thresholding using the value in ``threshold``.
    - ``target`` (:class:`~torch.Tensor`): An int tensor of shape ``(N, ...)``.

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

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

    - ``bck`` (: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_bound      ?NZlinearZ	quadraticnone)	thresholdignore_indexweightsvalidate_argskwargsreturnc                    s<   t  j||fd dd| |r,t||| || _|| _d S NF)	normalizer#   )super__init__r   r"   r#   )selfr    r!   r"   r#   r$   	__class__ p/var/www/html/stable-diffusion-webui/venv/lib/python3.9/site-packages/torchmetrics/classification/cohen_kappa.pyr)   b   s
    zBinaryCohenKappa.__init__r%   c                 C   s   t | j| jS zCompute metric.r   Zconfmatr"   r*   r-   r-   r.   computep   s    zBinaryCohenKappa.computevalaxr%   c                 C   s   |  ||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)

        Z_plotr*   r5   r6   r-   r-   r.   plott   s    (r   )r   NNT)NN)__name__
__module____qualname____doc__r   bool__annotations__r   r   r   floatr   r   intr   r   r)   r   r3   r   r   r   r   r9   __classcell__r-   r-   r+   r.   r   #   s0   
8    
 r   c                       s   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eee eed  eedd fddZedddZdeeeee f  ee edddZ  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, ...)``.

    .. note::
       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 specifing 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   ZClassplot_legend_nameNr   )num_classesr!   r"   r#   r$   r%   c                    s<   t  j||fd dd| |r,t||| || _|| _d S r&   )r(   r)   r   r"   r#   )r*   rE   r!   r"   r#   r$   r+   r-   r.   r)      s
    zMulticlassCohenKappa.__init__r/   c                 C   s   t | j| jS r0   r1   r2   r-   r-   r.   r3      s    zMulticlassCohenKappa.computer4   c                 C   s   |  ||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)

        r7   r8   r-   r-   r.   r9      s    (r   )NNT)NN)r:   r;   r<   r=   r   r>   r?   r   r   r   r@   r   rD   strrA   r   r   r   r)   r   r3   r   r   r   r   r9   rB   r-   r-   r+   r.   rC      s0   
;   
 rC   c                
   @   sB   e Zd ZdZd
ed eee eed  ee ee	e
ddd	ZdS )
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)

    r   NT)binaryZ
multiclassr   )taskr    rE   r"   r!   r#   r$   r%   c                 K   s   t |}||||d |t jkr6t|fi |S |t jkrnt|ts^tdt	| dt
|fi |S td| ddS )zInitialize task metric.)r"   r!   r#   z+`num_classes` is expected to be `int` but `z was passed.`zTask z not supported!N)r   Zfrom_strupdateBINARYr   Z
MULTICLASS
isinstancerA   
ValueErrortyperC   )clsrI   r    rE   r"   r!   r#   r$   r-   r-   r.   __new__:  s    



zCohenKappa.__new__)r   NNNT)r:   r;   r<   r=   r   r@   r   rA   r>   r   r   rP   r-   r-   r-   r.   rG     s         
rG   N)typingr   r   r   r   Ztorchr   Ztyping_extensionsr   Z torchmetrics.classification.baser   Z,torchmetrics.classification.confusion_matrixr	   r
   Z2torchmetrics.functional.classification.cohen_kappar   r   r   Ztorchmetrics.metricr   Ztorchmetrics.utilities.enumsr   Ztorchmetrics.utilities.importsr   Ztorchmetrics.utilities.plotr   r   Z__doctest_skip__r   rC   rG   r-   r-   r-   r.   <module>   s   | 