o
    .wiG                     @   s   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	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mZ esFg d	ZG d
d deZG dd deZG dd deZdS )    )Sequence)AnyOptionalUnionN)Tensor)+_multilabel_confusion_matrix_arg_validation#_multilabel_confusion_matrix_format!_multilabel_coverage_error_update,_multilabel_ranking_average_precision_update_multilabel_ranking_loss_update%_multilabel_ranking_tensor_validation_ranking_reduce)Metric)_MATPLOTLIB_AVAILABLE)_AX_TYPE_PLOT_OUT_TYPE)MultilabelCoverageError.plot&MultilabelRankingAveragePrecision.plotMultilabelRankingLoss.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
Zeed< 		ddedee 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	d deeeee f  dee defddZ  ZS )!MultilabelCoverageErrora  Compute `Multilabel coverage error`_.

    The score measure how far we need to go through the ranked scores to cover all true labels. The best value is equal
    to the average number of labels in the target tensor per sample.

    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 sigmoid per element.
    - ``target`` (:class:`~torch.Tensor`): An int tensor of shape ``(N, C, ...)``. Target should be a tensor
      containing ground truth labels, and therefore only contain {0,1} values (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:

    - ``mlce`` (:class:`~torch.Tensor`): A tensor containing the multilabel coverage error.

    Args:
        num_labels: Integer specifying the number of labels
        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.

    Example:
        >>> from torch import rand, randint
        >>> from torchmetrics.classification import MultilabelCoverageError
        >>> preds = rand(10, 5)
        >>> target = randint(2, (10, 5))
        >>> mlce = MultilabelCoverageError(num_labels=5)
        >>> mlce(preds, target)
        tensor(3.9000)

    Fhigher_is_betteris_differentiablefull_state_update        plot_lower_bound      ?plot_upper_boundLabelplot_legend_nameNT
num_labelsignore_indexvalidate_argskwargsreturnc                    f   t  jdi | |rt|d|d || _|| _|| _| jdtddd | jdtddd d S Nr   )	thresholdr!   measuresum)dist_reduce_fxtotal 	super__init__r   r"   r    r!   	add_statetorchtensorselfr    r!   r"   r#   	__class__r,   `/home/ubuntu/sommelier/.venv/lib/python3.10/site-packages/torchmetrics/classification/ranking.pyr/   W      z MultilabelCoverageError.__init__predstargetc                 C   s   | j rt||| j| j t||| jd| jdd\}}t||\}}t| jts2t	dt
| j dt| jtsCt	dt
| j d|  j|7  _|  j|7  _dS zUpdate metric states.r   F)r'   r!   should_threshold6Expected 'self.measure' to be of type Tensor, but got .4Expected 'self.total' to be of type Tensor, but got N)r"   r   r    r!   r   r	   
isinstancer(   r   	TypeErrortyper+   r4   r9   r:   r(   num_elementsr,   r,   r7   updateg   s   
zMultilabelCoverageError.updatec                 C   Z   t | jtstdt| j dt | jts"tdt| j dt| jt| j S zCompute metric.r=   r>   r?   	r@   r(   r   rA   rB   r+   r   intitemr4   r,   r,   r7   computex   
   zMultilabelCoverageError.computevalaxc                 C      |  ||S )ay  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 MultilabelCoverageError
            >>> metric = MultilabelCoverageError(num_labels=3)
            >>> metric.update(rand(20, 3), randint(2, (20, 3)))
            >>> fig_, ax_ = metric.plot()

        .. plot::
            :scale: 75

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

        _plotr4   rN   rO   r,   r,   r7   plot      (r   NTNN__name__
__module____qualname____doc__r   bool__annotations__r   r   r   floatr   r   strrI   r   r   r/   r   rE   rL   r   r   r   r   rT   __classcell__r,   r,   r5   r7   r   )   s>   
 &
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dedee 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	d deeeee f  dee defddZ  ZS )!!MultilabelRankingAveragePrecisiona"  Compute label ranking average precision score for multilabel data [1].

    The score is the average over each ground truth label assigned to each sample of the ratio of true vs. total labels
    with lower score. Best score is 1.

    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 sigmoid per element.
    - ``target`` (:class:`~torch.Tensor`): An int tensor of shape ``(N, C, ...)``. Target should be a tensor
      containing ground truth labels, and therefore only contain {0,1} values (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:

    - ``mlrap`` (:class:`~torch.Tensor`): A tensor containing the multilabel ranking average precision.

    Args:
        num_labels: Integer specifying the number of labels
        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.

    Example:
        >>> from torch import rand, randint
        >>> from torchmetrics.classification import MultilabelRankingAveragePrecision
        >>> preds = rand(10, 5)
        >>> target = randint(2, (10, 5))
        >>> mlrap = MultilabelRankingAveragePrecision(num_labels=5)
        >>> mlrap(preds, target)
        tensor(0.7744)

    Tr   Fr   r   r   r   r   r   r   r   Nr    r!   r"   r#   r$   c                    r%   r&   r-   r3   r5   r,   r7   r/      r8   z*MultilabelRankingAveragePrecision.__init__r9   r:   c                 C      | j rt||| j| j t||| jd| jdd\}}t| jts+tdt	| j dt| j
ts<tdt	| j
 dt||\}}|  j|7  _|  j
|7  _
dS r;   )r"   r   r    r!   r   r@   r(   r   rA   rB   r+   r
   rC   r,   r,   r7   rE         
z(MultilabelRankingAveragePrecision.updatec                 C   rF   rG   rH   rK   r,   r,   r7   rL      rM   z)MultilabelRankingAveragePrecision.computerN   rO   c                 C   rP   )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 rand, randint
            >>> # Example plotting a single value
            >>> from torchmetrics.classification import MultilabelRankingAveragePrecision
            >>> metric = MultilabelRankingAveragePrecision(num_labels=3)
            >>> metric.update(rand(20, 3), randint(2, (20, 3)))
            >>> fig_, ax_ = metric.plot()

        .. plot::
            :scale: 75

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

        rQ   rS   r,   r,   r7   rT     rU   r   rV   rW   rX   r,   r,   r5   r7   rb      s>   
 &
rb   c                       r   )!MultilabelRankingLossa  Compute the label ranking loss for multilabel data [1].

    The score is corresponds to the average number of label pairs that are incorrectly ordered given some predictions
    weighted by the size of the label set and the number of labels not in the label set. The best score is 0.

    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 sigmoid per element.
    - ``target`` (:class:`~torch.Tensor`): An int tensor of shape ``(N, C, ...)``. Target should be a tensor
      containing ground truth labels, and therefore only contain {0,1} values (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:

    - ``mlrl`` (:class:`~torch.Tensor`): A tensor containing the multilabel ranking loss.

    Args:
        preds: Tensor with predictions
        target: Tensor with true labels
        num_labels: Integer specifying the number of labels
        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.

    Example:
        >>> from torch import rand, randint
        >>> from torchmetrics.classification import MultilabelRankingLoss
        >>> preds = rand(10, 5)
        >>> target = randint(2, (10, 5))
        >>> mlrl = MultilabelRankingLoss(num_labels=5)
        >>> mlrl(preds, target)
        tensor(0.4167)

    Fr   r   r   r   r   r   r   r   r   NTr    r!   r"   r#   r$   c                    r%   r&   r-   r3   r5   r,   r7   r/   ^  r8   zMultilabelRankingLoss.__init__r9   r:   c                 C   rc   r;   )r"   r   r    r!   r   r@   r(   r   rA   rB   r+   r   rC   r,   r,   r7   rE   n  rd   zMultilabelRankingLoss.updatec                 C   rF   rG   rH   rK   r,   r,   r7   rL   ~  rM   zMultilabelRankingLoss.computerN   rO   c                 C   rP   )aq  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 MultilabelRankingLoss
            >>> metric = MultilabelRankingLoss(num_labels=3)
            >>> metric.update(rand(20, 3), randint(2, (20, 3)))
            >>> fig_, ax_ = metric.plot()

        .. plot::
            :scale: 75

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

        rQ   rS   r,   r,   r7   rT     rU   r   rV   rW   rX   r,   r,   r5   r7   re   .  s>   
 (
re   )collections.abcr   typingr   r   r   r1   r   .torchmetrics.functional.classification.rankingr   r   r	   r
   r   r   r   torchmetrics.metricr   torchmetrics.utilities.importsr   torchmetrics.utilities.plotr   r   __doctest_skip__r   rb   re   r,   r,   r,   r7   <module>   s   $	  