a
    dS,                     @   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 d dl	m
Z
 eedddZeeed	d
dZdeeeee ddddZeeeeef dddZdeeeee eedddZeeeeef dddZd eeeee eedddZeeeeef dddZd!eeeee eedddZdS )"    )OptionalTupleN)Tensor)+_multilabel_confusion_matrix_arg_validation#_multilabel_confusion_matrix_format._multilabel_confusion_matrix_tensor_validation)_cumsum)xreturnc                 C   sT   t  ( t j| dddd\}}}W d   n1 s60    Y  t|dd}|| S )zRank data based on values.T)sortedZreturn_inverseZreturn_countsNr   Zdim)torchZno_graduniquer   )r	   _inversecountsZranks r   w/var/www/html/stable-diffusion-webui/venv/lib/python3.9/site-packages/torchmetrics/functional/classification/ranking.py
_rank_data   s    
6r   )score
n_elementsr
   c                 C   s   | | S )Nr   )r   r   r   r   r   _ranking_reduce$   s    r   )predstarget
num_labelsignore_indexr
   c                 C   s*   t | ||| |  s&td| j d S )NzJExpected preds tensor to be floating point, but received input with dtype )r   Zis_floating_point
ValueErrorZdtype)r   r   r   r   r   r   r   %_multilabel_ranking_tensor_validation(   s    r   )r   r   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   Z
zeros_likeminabssumtofloat32Znumel)r   r   offsetZ	preds_modZ	preds_mincoverager   r   r   !_multilabel_coverage_error_update0   s    
$r'   T)r   r   r   r   validate_argsr
   c                 C   sP   |r t |d|d t| ||| t| ||d|dd\} }t| |\}}t||S )a  Compute 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r+   r   Zshould_threshold)r   r   r   r'   r   )r   r   r   r   r(   r&   totalr   r   r   multilabel_coverage_error:   s    ,
r.   c                 C   s   |  }t jd|jd}|j\}}t|D ]p}|| dk}t|| |  }t|dkrt||k rt|| |  }	||	  }
n
t 	|}
||
7 }q(||fS )z5Accumulate state for label ranking average precision.r)   devicer   r   )
r   tensorr0   shaperanger   floatlenmeanZ	ones_like)r   r   Z	neg_predsr   n_predsn_labelsirelevantZrankingZrankZ	score_idxr   r   r   ,_multilabel_ranking_average_precision_updatep   s    


r;   c                 C   sP   |r t |d|d t| ||| t| ||d|dd\} }t| |\}}t||S )a  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.

    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.

    r)   r*   Fr,   )r   r   r   r;   r   )r   r   r   r   r(   r   r   r   r   r   $multilabel_ranking_average_precision   s    ,
r<   c                 C   s   | j \}}|dk}|jdd}|dk||k @ }| | } || }|| }t| dkrft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   r)   r/   g      ?)	r2   r"   r5   r   r1   r0   Zargsortr#   r$   )r   r   r7   r8   r:   Z
n_relevantmaskr   Zper_label_lossZ
correctionZdenomlossr   r   r   _multilabel_ranking_loss_update   s    	
r?   c                 C   sP   |r t |d|d t| ||| t| ||d|dd\} }t| |\}}t||S )a  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.

    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.

    r)   r*   Fr,   )r   r   r   r?   r   )r   r   r   r   r(   r>   r   r   r   r   multilabel_ranking_loss   s    ,
r@   )N)NT)NT)NT)typingr   r   r   r   Z7torchmetrics.functional.classification.confusion_matrixr   r   r   Ztorchmetrics.utilities.datar   r   intr   r   r'   boolr.   r;   r<   r?   r@   r   r   r   r   <module>   sX   	   6  6#  