o
    yiI%                     @   s   d dl mZmZ d dl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 G dd	 d	eZG d
d de	ZG dd dZdS )    )AnyOptionalN)Tensor)Literal)BinaryConfusionMatrixMulticlassConfusionMatrix)"_binary_cohen_kappa_arg_validation_cohen_kappa_reduce&_multiclass_cohen_kappa_arg_validation)Metricc                       s   e Zd ZU dZ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dZdefddZ  ZS )BinaryCohenKappaa	  Calculates `Cohen's kappa score`_ that measures inter-annotator agreement for binary tasks. It is defined
    as.

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

    Example (preds is float tensor):
        >>> from torchmetrics.classification import BinaryCohenKappa
        >>> target = torch.tensor([1, 1, 0, 0])
        >>> preds = torch.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      ?N	thresholdignore_indexweightslinear	quadraticnonevalidate_argskwargsreturnc                    <   t  j||fd dd| |rt||| || _|| _d S NF)	normalizer   )super__init__r   r   r   )selfr   r   r   r   r   	__class__ [/home/ubuntu/.local/lib/python3.10/site-packages/torchmetrics/classification/cohen_kappa.pyr   Y   
   
zBinaryCohenKappa.__init__c                 C      t | j| jS Nr	   confmatr   r    r#   r#   r$   computeg      zBinaryCohenKappa.compute)r   NNT)__name__
__module____qualname____doc__r   bool__annotations__r   r   floatr   intr   r   r   r   r+   __classcell__r#   r#   r!   r$   r      s.   
 7
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de	d	e
e	 d
e
ed  dededdf fddZdefddZ  ZS )MulticlassCohenKappaa
  Calculates `Cohen's kappa score`_ that measures inter-annotator agreement for multiclass tasks. It is
    defined as.

    .. 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 torchmetrics.classification import MulticlassCohenKappa
        >>> target = torch.tensor([2, 1, 0, 0])
        >>> preds = torch.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 = torch.tensor([2, 1, 0, 0])
        >>> preds = torch.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   Nnum_classesr   r   r   r   r   r   c                    r   r   )r   r   r
   r   r   )r    r7   r   r   r   r   r!   r#   r$   r      r%   zMulticlassCohenKappa.__init__c                 C   r&   r'   r(   r*   r#   r#   r$   r+      r,   zMulticlassCohenKappa.compute)NNT)r-   r.   r/   r0   r   r1   r2   r   r   r4   r   r   r   r   r   r+   r5   r#   r#   r!   r$   r6   k   s,   
 <
r6   c                   @   sZ   e Zd ZdZ					dded dedee d	eed
  dee dede	de
fddZdS )
CohenKappaa  Calculates `Cohen's kappa score`_ that measures inter-annotator agreement. It is defined as.

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

    Legacy Example:
        >>> target = torch.tensor([1, 1, 0, 0])
        >>> preds = torch.tensor([0, 1, 0, 0])
        >>> cohenkappa = CohenKappa(task="multiclass", num_classes=2)
        >>> cohenkappa(preds, target)
        tensor(0.5000)
    r   NTtask)binary
multiclassr   r7   r   r   r   r   r   r   c                 K   s`   | t|||d |dkrt|fi |S |dkr)t|ts!J t|fi |S td| )N)r   r   r   r:   r;   z[Expected argument `task` to either be `'binary'`, `'multiclass'` or `'multilabel'` but got )updatedictr   
isinstancer4   r6   
ValueError)clsr9   r   r7   r   r   r   r   r#   r#   r$   __new__   s   
zCohenKappa.__new__)r   NNNT)r-   r.   r/   r0   r   r3   r   r4   r1   r   r   rA   r#   r#   r#   r$   r8      s0    
	r8   )typingr   r   torchr   typing_extensionsr   torchmetrics.classificationr   r   2torchmetrics.functional.classification.cohen_kappar   r	   r
   torchmetrics.metricr   r   r6   r8   r#   r#   r#   r$   <module>   s   NS