o
    yi,                     @   sh  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 dedefddZ	d	ed
e
defddZ	d!dedede
dee
 ddf
ddZdededeee
f fddZ		d"dedede
dee
 dedefddZdededeee
f fddZ		d"dedede
dee
 dedefddZdededeee
f fddZ		d"dedede
dee
 dedefdd ZdS )#    )OptionalTupleN)Tensor)+_multilabel_confusion_matrix_arg_validation#_multilabel_confusion_matrix_format._multilabel_confusion_matrix_tensor_validationxreturnc                 C   sT   t   t j| dddd\}}}W d   n1 sw   Y  |jdd}|| S )zRank data based on values.T)sortedreturn_inversereturn_countsNr   dim)torchno_graduniquecumsum)r   _inversecountsranks r   b/home/ubuntu/.local/lib/python3.10/site-packages/torchmetrics/functional/classification/ranking.py
_rank_data   s
   
r   score
n_elementsc                 C   s   | | S Nr   )r   r   r   r   r   _ranking_reduce#   s   r   predstarget
num_labelsignore_indexc                 C   s*   t | ||| |  std| j d S )NzJExpected preds tensor to be floating point, but received input with dtype )r   is_floating_point
ValueErrordtype)r   r   r    r!   r   r   r   %_multilabel_ranking_tensor_validation'   s   r%   c                 C   sn   t | }|   d ||dk< | | }|jddd }| |dddf kjddt j}| | fS )z$Accumulate state for coverage error.
   r      r   N)r   
zeros_likeminabssumtofloat32numel)r   r   offset	preds_mod	preds_mincoverager   r   r   !_multilabel_coverage_error_update/   s   
$r3   Tvalidate_argsc                 C   P   |rt |d|d t| ||| t| ||d|dd\} }t| |\}}t||S )a  Computes multilabel coverage error [1]. 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.

    Accepts the following input tensors:

    - ``preds`` (float tensor): ``(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`` (int tensor): ``(N, C, ...)``. Target should be a tensor containing ground truth labels, and therefore
      only contain {0,1} values (except if `ignore_index` is specified).

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

    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.functional.classification import multilabel_coverage_error
        >>> _ = torch.manual_seed(42)
        >>> preds = torch.rand(10, 5)
        >>> target = torch.randint(2, (10, 5))
        >>> multilabel_coverage_error(preds, target, num_labels=5)
        tensor(3.9000)

    References:
        [1] Tsoumakas, G., Katakis, I., & Vlahavas, I. (2010). Mining multi-label data. In Data mining and
        knowledge discovery handbook (pp. 667-685). Springer US.
            	thresholdr!   Fr8   r!   should_threshold)r   r%   r   r3   r   )r   r   r    r!   r4   r2   totalr   r   r   multilabel_coverage_error9   s   )

r<   c                 C   s   |  }t jd|jd}|j\}}t|D ]5}|| dk}t|| |  }t|dkrCt||k rCt|| |  }	||	  }
nd}
||
7 }q||fS )z5Accumulate state for label ranking average precision.r6   devicer'   r   g      ?)	r   tensorr>   shaperanger   floatlenmean)r   r   	neg_predsr   n_predsn_labelsirelevantrankingrank	score_idxr   r   r   ,_multilabel_ranking_average_precision_updatel   s   

rM   c                 C   r5   )a  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.

    Accepts the following input tensors:

    - ``preds`` (float tensor): ``(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`` (int tensor): ``(N, C, ...)``. Target should be a tensor containing ground truth labels, and therefore
      only contain {0,1} values (except if `ignore_index` is specified).

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

    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.functional.classification import multilabel_ranking_average_precision
        >>> _ = torch.manual_seed(42)
        >>> preds = torch.rand(10, 5)
        >>> target = torch.randint(2, (10, 5))
        >>> multilabel_ranking_average_precision(preds, target, num_labels=5)
        tensor(0.7744)

    References:
        [1] Tsoumakas, G., Katakis, I., & Vlahavas, I. (2010). Mining multi-label data. In Data mining and
        knowledge discovery handbook (pp. 667-685). Springer US.
    r6   r7   Fr9   )r   r%   r   rM   r   )r   r   r    r!   r4   r   r   r   r   r   $multilabel_ranking_average_precision      *

rN   c                 C   s   | j \}}|dk}|jdd}|dk||k @ }| | } || }|| }t| dkr3tjd| jddfS | jddjdd}|| | tj}d| |d  }	|||  }
|jdd|	 |
 }| |fS )zAccumulate state for label ranking loss.

    Args:
        preds: tensor with predictions
        target: tensor with ground truth labels
        sample_weight: optional tensor with weight for each sample
    r'   r   r   r6   r=   g      ?)	r@   r+   rC   r   r?   r>   argsortr,   r-   )r   r   rF   rG   rI   
n_relevantmaskr   per_label_loss
correctiondenomlossr   r   r   _multilabel_ranking_loss_update   s   
rW   c                 C   r5   )a  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.

    Accepts the following input tensors:

    - ``preds`` (float tensor): ``(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`` (int tensor): ``(N, C, ...)``. Target should be a tensor containing ground truth labels, and therefore
      only contain {0,1} values (except if `ignore_index` is specified).

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

    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.functional.classification import multilabel_ranking_loss
        >>> _ = torch.manual_seed(42)
        >>> preds = torch.rand(10, 5)
        >>> target = torch.randint(2, (10, 5))
        >>> multilabel_ranking_loss(preds, target, num_labels=5)
        tensor(0.4167)

    References:
        [1] Tsoumakas, G., Katakis, I., & Vlahavas, I. (2010). Mining multi-label data. In Data mining and
        knowledge discovery handbook (pp. 667-685). Springer US.
    r6   r7   Fr9   )r   r%   r   rW   r   )r   r   r    r!   r4   rV   r   r   r   r   multilabel_ranking_loss   rO   rX   r   )NT)typingr   r   r   r   7torchmetrics.functional.classification.confusion_matrixr   r   r   r   intr   r%   r3   boolr<   rM   rN   rW   rX   r   r   r   r   <module>   s   	

3
4"