o
    yiD*                     @   s   d dl 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 G dd deZG dd	 d	eZG d
d deZdS )    )AnyOptionalN)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)Metricc                          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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 )MultilabelCoverageErrora  Computes `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).

    .. note::
       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 specifing 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 torchmetrics.classification import MultilabelCoverageError
        >>> _ = torch.manual_seed(42)
        >>> preds = torch.rand(10, 5)
        >>> target = torch.randint(2, (10, 5))
        >>> mlce = MultilabelCoverageError(num_labels=5)
        >>> mlce(preds, target)
        tensor(3.9000)
    Fhigher_is_betteris_differentiablefull_state_updateNT
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 N        )	thresholdr   measuresum)dist_reduce_fxtotal 	super__init__r   r   r   r   	add_statetorchtensorselfr   r   r   r   	__class__r   W/home/ubuntu/.local/lib/python3.10/site-packages/torchmetrics/classification/ranking.pyr"   G      z MultilabelCoverageError.__init__predstargetc                 C   b   | j rt||| j| j t||| jd| jdd\}}t||\}}|  j|7  _|  j|7  _d S Nr   F)r   r   should_threshold)r   r
   r   r   r   r   r   r   r'   r,   r-   r   
n_elementsr   r   r*   updateW      
zMultilabelCoverageError.updatec                 C      t | j| jS Nr   r   r   r'   r   r   r*   computea      zMultilabelCoverageError.computeNT__name__
__module____qualname____doc__r   bool__annotations__r   r   intr   r   r"   r   r3   r9   __classcell__r   r   r(   r*   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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  ZS )!MultilabelRankingAveragePrecisiona'  Computes 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).

    .. note::
       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 specifing 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 torchmetrics.classification import MultilabelRankingAveragePrecision
        >>> _ = torch.manual_seed(42)
        >>> preds = torch.rand(10, 5)
        >>> target = torch.randint(2, (10, 5))
        >>> mlrap = MultilabelRankingAveragePrecision(num_labels=5)
        >>> mlrap(preds, target)
        tensor(0.7744)
    Tr   Fr   r   Nr   r   r   r   r   c                    r   r   r    r&   r(   r   r*   r"      r+   z*MultilabelRankingAveragePrecision.__init__r,   r-   c                 C   r.   r/   )r   r
   r   r   r   r   r   r   r1   r   r   r*   r3      r4   z(MultilabelRankingAveragePrecision.updatec                 C   r5   r6   r7   r8   r   r   r*   r9      r:   z)MultilabelRankingAveragePrecision.computer;   r<   r   r   r(   r*   rE   e   s(   
 $
rE   c                       r   )MultilabelRankingLossa  Computes 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).

    .. note::
       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 specifing 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 torchmetrics.classification import MultilabelRankingLoss
        >>> _ = torch.manual_seed(42)
        >>> preds = torch.rand(10, 5)
        >>> target = torch.randint(2, (10, 5))
        >>> mlrl = MultilabelRankingLoss(num_labels=5)
        >>> mlrl(preds, target)
        tensor(0.4167)
    Fr   r   r   NTr   r   r   r   r   c                    r   r   r    r&   r(   r   r*   r"      r+   zMultilabelRankingLoss.__init__r,   r-   c                 C   r.   r/   )r   r
   r   r   r   r	   r   r   r1   r   r   r*   r3      r4   zMultilabelRankingLoss.updatec                 C   r5   r6   r7   r8   r   r   r*   r9      r:   zMultilabelRankingLoss.computer;   r<   r   r   r(   r*   rF      s(   
 &
rF   )typingr   r   r$   r   .torchmetrics.functional.classification.rankingr   r   r   r   r	   r
   r   torchmetrics.metricr   r   rE   rF   r   r   r   r*   <module>   s   $	FG