o
    yi[?                     @   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	m
Z
mZmZmZmZmZmZmZmZmZ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eZG dd dZdS )    )AnyOptionalN)Tensor)Literal)'_binary_confusion_matrix_arg_validation _binary_confusion_matrix_compute_binary_confusion_matrix_format*_binary_confusion_matrix_tensor_validation_binary_confusion_matrix_update+_multiclass_confusion_matrix_arg_validation$_multiclass_confusion_matrix_compute#_multiclass_confusion_matrix_format._multiclass_confusion_matrix_tensor_validation#_multiclass_confusion_matrix_update+_multilabel_confusion_matrix_arg_validation$_multilabel_confusion_matrix_compute#_multilabel_confusion_matrix_format._multilabel_confusion_matrix_tensor_validation#_multilabel_confusion_matrix_update)Metricc                       s   e Zd ZU dZdZeed< dZe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deddfddZdefddZ  ZS )BinaryConfusionMatrixa  Computes the `confusion matrix`_ for binary tasks.

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

    - ``preds`` (:class:`~torch.Tensor`): An 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:

    - ``bcm`` (:class:`~torch.Tensor`): A tensor containing a ``(2, 2)`` matrix

    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
        normalize: Normalization mode for confusion matrix. Choose from:

            - ``None`` or ``'none'``: no normalization (default)
            - ``'true'``: normalization over the targets (most commonly used)
            - ``'pred'``: normalization over the predictions
            - ``'all'``: normalization over the whole matrix
        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 BinaryConfusionMatrix
        >>> target = torch.tensor([1, 1, 0, 0])
        >>> preds = torch.tensor([0, 1, 0, 0])
        >>> bcm = BinaryConfusionMatrix()
        >>> bcm(preds, target)
        tensor([[2, 0],
                [1, 1]])

    Example (preds is float tensor):
        >>> from torchmetrics.classification import BinaryConfusionMatrix
        >>> target = torch.tensor([1, 1, 0, 0])
        >>> preds = torch.tensor([0.35, 0.85, 0.48, 0.01])
        >>> bcm = BinaryConfusionMatrix()
        >>> bcm(preds, target)
        tensor([[2, 0],
                [1, 1]])
    Fis_differentiableNhigher_is_betterfull_state_update      ?T	thresholdignore_index	normalizetruepredallnonevalidate_argskwargsreturnc                    s\   t  jdi | |rt||| || _|| _|| _|| _| jdtj	ddtj
ddd d S Nconfmat   dtypesumdist_reduce_fx )super__init__r   r   r   r   r#   	add_statetorchzeroslong)selfr   r   r   r#   r$   	__class__r.   `/home/ubuntu/.local/lib/python3.10/site-packages/torchmetrics/classification/confusion_matrix.pyr0   ]      "zBinaryConfusionMatrix.__init__predstargetc                 C   sF   | j r
t||| j t||| j| j\}}t||}|  j|7  _dS z*Update state with predictions and targets.N)r#   r	   r   r   r   r
   r'   r5   r:   r;   r'   r.   r.   r8   updateo   s
   
zBinaryConfusionMatrix.updatec                 C      t | j| jS zComputes confusion matrix.)r   r'   r   r5   r.   r.   r8   computew      zBinaryConfusionMatrix.computer   NNT)__name__
__module____qualname____doc__r   bool__annotations__r   r   r   floatintr   r   r0   r   r>   rB   __classcell__r.   r.   r6   r8   r   (   s0   
 0
r   c                       s   e Zd ZU dZdZeed< dZe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deddfddZdefddZ  ZS )MulticlassConfusionMatrixa  Computes the `confusion matrix`_ for multiclass tasks.

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

    - ``preds`` (:class:`~torch.Tensor`): An 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:

    - ``bcm`` (:class:`~torch.Tensor`): A tensor containing a ``(2, 2)`` matrix

    ---

    As input to 'update' the metric accepts the following input:

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

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

    As output of 'compute' the metric returns the following output:

    - ``confusion matrix``: [num_classes, num_classes] matrix

    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
        normalize: Normalization mode for confusion matrix. Choose from:

            - ``None`` or ``'none'``: no normalization (default)
            - ``'true'``: normalization over the targets (most commonly used)
            - ``'pred'``: normalization over the predictions
            - ``'all'``: normalization over the whole matrix
        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 MulticlassConfusionMatrix
        >>> target = torch.tensor([2, 1, 0, 0])
        >>> preds = torch.tensor([2, 1, 0, 1])
        >>> metric = MulticlassConfusionMatrix(num_classes=3)
        >>> metric(preds, target)
        tensor([[1, 1, 0],
                [0, 1, 0],
                [0, 0, 1]])

    Example (pred is float tensor):
        >>> from torchmetrics.classification import MulticlassConfusionMatrix
        >>> 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 = MulticlassConfusionMatrix(num_classes=3)
        >>> metric(preds, target)
        tensor([[1, 1, 0],
                [0, 1, 0],
                [0, 0, 1]])
    Fr   Nr   r   Tnum_classesr   r   r"   r   r    r!   r#   r$   r%   c                    s\   t  jdi | |rt||| || _|| _|| _|| _| jdtj	||tj
ddd d S )Nr'   r)   r+   r,   r.   )r/   r0   r   rO   r   r   r#   r1   r2   r3   r4   )r5   rO   r   r   r#   r$   r6   r.   r8   r0      r9   z"MulticlassConfusionMatrix.__init__r:   r;   c                 C   sJ   | j rt||| j| j t||| j\}}t||| j}|  j|7  _dS r<   )r#   r   rO   r   r   r   r'   r=   r.   r.   r8   r>      s
   z MulticlassConfusionMatrix.updatec                 C   r?   r@   )r   r'   r   rA   r.   r.   r8   rB      rC   z!MulticlassConfusionMatrix.compute)NNT)rE   rF   rG   rH   r   rI   rJ   r   r   r   rL   r   r   r0   r   r>   rB   rM   r.   r.   r6   r8   rN   |   s.   
 F
rN   c                       s   e Zd ZU dZdZeed< dZee ed< dZ	eed< 				dd	e
d
edee
 deed  dededdf fddZdededdfddZdefddZ  ZS )MultilabelConfusionMatrixaq	  Computes the `confusion matrix`_ for multilabel tasks.

    As input to 'update' the metric accepts the following input:

    - ``preds`` (int or float tensor): ``(N, C, ...)``. 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`` (int tensor): ``(N, C, ...)``

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

    As output of 'compute' the metric returns the following output:

    - ``confusion matrix``: [num_labels,2,2] matrix

    Args:
        num_classes: Integer specifing the number of labels
        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
        normalize: Normalization mode for confusion matrix. Choose from:

            - ``None`` or ``'none'``: no normalization (default)
            - ``'true'``: normalization over the targets (most commonly used)
            - ``'pred'``: normalization over the predictions
            - ``'all'``: normalization over the whole matrix
        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 MultilabelConfusionMatrix
        >>> target = torch.tensor([[0, 1, 0], [1, 0, 1]])
        >>> preds = torch.tensor([[0, 0, 1], [1, 0, 1]])
        >>> metric = MultilabelConfusionMatrix(num_labels=3)
        >>> metric(preds, target)
        tensor([[[1, 0], [0, 1]],
                [[1, 0], [1, 0]],
                [[0, 1], [0, 1]]])

    Example (preds is float tensor):
        >>> from torchmetrics.classification import MultilabelConfusionMatrix
        >>> target = torch.tensor([[0, 1, 0], [1, 0, 1]])
        >>> preds = torch.tensor([[0.11, 0.22, 0.84], [0.73, 0.33, 0.92]])
        >>> metric = MultilabelConfusionMatrix(num_labels=3)
        >>> metric(preds, target)
        tensor([[[1, 0], [0, 1]],
                [[1, 0], [1, 0]],
                [[0, 1], [0, 1]]])
    Fr   Nr   r   r   T
num_labelsr   r   r   rP   r#   r$   r%   c                    sf   t  jdi | |rt|||| || _|| _|| _|| _|| _| jdt	j
|ddt	jddd d S r&   )r/   r0   r   rR   r   r   r   r#   r1   r2   r3   r4   )r5   rR   r   r   r   r#   r$   r6   r.   r8   r0     s   	$z"MultilabelConfusionMatrix.__init__r:   r;   c                 C   sR   | j rt||| j| j t||| j| j| j\}}t||| j}|  j|7  _dS r<   )r#   r   rR   r   r   r   r   r'   r=   r.   r.   r8   r>   1  s   z MultilabelConfusionMatrix.updatec                 C   r?   r@   )r   r'   r   rA   r.   r.   r8   rB   ;  rC   z!MultilabelConfusionMatrix.computerD   )rE   rF   rG   rH   r   rI   rJ   r   r   r   rL   rK   r   r   r0   r   r>   rB   rM   r.   r.   r6   r8   rQ      s4   
 2

rQ   c                   @   sd   e Zd ZdZ						dded dedee d	ee d
eed  dee dede	de
fddZdS )ConfusionMatrixa$  Computes the `confusion matrix`_.

    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'``, ``'multiclass'`` or ``multilabel``. See the documentation of
    :mod:`BinaryConfusionMatrix`, :mod:`MulticlassConfusionMatrix` and :func:`MultilabelConfusionMatrix` 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])
        >>> confmat = ConfusionMatrix(task="binary", num_classes=2)
        >>> confmat(preds, target)
        tensor([[2, 0],
                [1, 1]])

        >>> target = torch.tensor([2, 1, 0, 0])
        >>> preds = torch.tensor([2, 1, 0, 1])
        >>> confmat = ConfusionMatrix(task="multiclass", num_classes=3)
        >>> confmat(preds, target)
        tensor([[1, 1, 0],
                [0, 1, 0],
                [0, 0, 1]])

        >>> target = torch.tensor([[0, 1, 0], [1, 0, 1]])
        >>> preds = torch.tensor([[0, 0, 1], [1, 0, 1]])
        >>> confmat = ConfusionMatrix(task="multilabel", num_labels=3)
        >>> confmat(preds, target)
        tensor([[[1, 0], [0, 1]],
                [[1, 0], [1, 0]],
                [[0, 1], [0, 1]]])
    r   NTtask)binary
multiclass
multilabelr   rO   rR   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 |dkr=t|ts4J t||fi |S td| )N)r   r   r#   rU   rV   rW   z[Expected argument `task` to either be `'binary'`, `'multiclass'` or `'multilabel'` but got )r>   dictr   
isinstancerL   rN   rQ   
ValueError)	clsrT   r   rO   rR   r   r   r#   r$   r.   r.   r8   __new__a  s   zConfusionMatrix.__new__)r   NNNNT)rE   rF   rG   rH   r   rK   r   rL   rI   r   r   r\   r.   r.   r.   r8   rS   @  s6    #
	
rS   )typingr   r   r2   r   typing_extensionsr   7torchmetrics.functional.classification.confusion_matrixr   r   r   r	   r
   r   r   r   r   r   r   r   r   r   r   torchmetrics.metricr   r   rN   rQ   rS   r.   r.   r.   r8   <module>   s   DTjZ