§
    ’©ºjPB  ã                   óÊ  — 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 d dlmZ d dlmZ ded	ed
edeeeef         fd„Z	 	 d&ded	ed
eeef         dededefd„Z	 	 d'deded         dee         ddfd„Z	 d(dededee         ddfd„Zdededeeef         fd„Z	 	 	 	 d)dedededed         dee         dedefd„Z	 	 d'dededed         dee         ddf
d„Z	 d(dedededee         ddf
d „Zdededeeef         fd!„Z	 	 	 	 d)dededededed         dee         dedefd"„Z	 	 	 	 	 d*deded#ed$         deded         dee         dee         dedefd%„ZdS )+é    )ÚOptionalÚUnionN)ÚTensor)ÚLiteral)Ú_binary_confusion_matrix_formatÚ*_binary_confusion_matrix_tensor_validationÚ#_multiclass_confusion_matrix_formatÚ._multiclass_confusion_matrix_tensor_validation)Únormalize_logits_if_needed)ÚClassificationTaskNoMultilabelÚconfidencesÚ
accuraciesÚbin_boundariesÚreturnc                 óÈ  — |                      | j        ¬¦  «        }t          j        t	          |¦  «        | j        | j        ¬¦  «        }t          j        t	          |¦  «        | j        | j        ¬¦  «        }t          j        t	          |¦  «        | j        | j        ¬¦  «        }t          j        | |d¬¦  «        dz
  }|                     d|t          j        | ¦  «        ¬¦  «         |                     d|| ¬¦  «         t          j	        ||z  ¦  «        }|                     d||¬¦  «         t          j	        ||z  ¦  «        }|| 
                    ¦   «         z  }|||fS )aª  Compute calibration bins using ``torch.bucketize``. Use for ``pytorch >=1.6``.

    Args:
        confidences: The confidence (i.e. predicted prob) of the top1 prediction.
        accuracies: 1.0 if the top-1 prediction was correct, 0.0 otherwise.
        bin_boundaries: Bin boundaries separating the ``linspace`` from 0 to 1.

    Returns:
        tuple with binned accuracy, binned confidence and binned probabilities

    )Údtype)Údevicer   T)Úrighté   r   )ÚdimÚindexÚsrc)Útor   ÚtorchÚzerosÚlenr   Ú	bucketizeÚscatter_add_Ú	ones_likeÚ
nan_to_numÚsum)r   r   r   Úacc_binÚconf_binÚ	count_binÚindicesÚprop_bins           úˆ/root/private/project/pallet_detection_v2/.venv/lib/python3.11/site-packages/torchmetrics/functional/classification/calibration_error.pyÚ_binning_bucketizer(      sH  € ð —’ [Ô%6�Ñ7Ô7€JÝŒk�#˜nÑ-Ô-°kÔ6HÐP[ÔPaÐbÑbÔb€GÝŒ{�3˜~Ñ.Ô.°{Ô7IÐQ\ÔQbÐcÑcÔc€HÝ”�C Ñ/Ô/¸Ô8JÐR]ÔRcÐdÑdÔd€IåŒo˜k¨>ÀÐFÑFÔFÈÑJ€Gà×Ò˜q¨µU´_À[Ñ5QÔ5QÐÑRÔRÐRà×Ò˜a w°KÐÑ@Ô@Ð@ÝÔ ¨9Ñ 4Ñ5Ô5€Hà×Ò˜Q g°:ÐÑ>Ô>Ð>ÝÔ˜w¨Ñ2Ñ3Ô3€Gà˜9Ÿ=š=™?œ?Ñ*€HØ�H˜hÐ&Ð&ó    Úl1FÚnormÚdebiasc                 óZ  — t          |t          ¦  «        r&t          j        dd|dz   | j        | j        ¬¦  «        }|dvrt          d|› �¦  «        ‚t          j        ¦   «         5  t          | ||¦  «        \  }}}ddd¦  «         n# 1 swxY w Y   |dk    r,t          j	        t          j
        ||z
  ¦  «        |z  ¦  «        S |dk    r)t          j        t          j
        ||z
  ¦  «        ¦  «        }|d	k    r²t          j	        t          j        ||z
  d
¦  «        |z  ¦  «        }|rU||dz
  z  |z  ||                     ¦   «         d         z  dz
  z  }	|t          j	        t          j        |	¦  «        ¦  «        z  }|dk    rt          j        |¦  «        nt          j        d¦  «        S |S )a¦  Compute the calibration error given the provided bin boundaries and norm.

    Args:
        confidences: The confidence (i.e. predicted prob) of the top1 prediction.
        accuracies: 1.0 if the top-1 prediction was correct, 0.0 otherwise.
        bin_boundaries: Bin boundaries separating the ``linspace`` from 0 to 1.
        norm: Norm function to use when computing calibration error. Defaults to "l1".
        debias: Apply debiasing to L2 norm computation as in
            `Verified Uncertainty Calibration`_. Defaults to False.

    Raises:
        ValueError: If an unsupported norm function is provided.

    Returns:
        Tensor: Calibration error scalar.

    r   r   )r   r   >   r*   Úl2ÚmaxzCArgument `norm` is expected to be one of 'l1', 'l2', 'max' but got Nr*   r/   r.   é   )Ú
isinstanceÚintr   Úlinspacer   r   Ú
ValueErrorÚno_gradr(   r!   Úabsr/   ÚpowÚsizer    ÚsqrtÚtensor)
r   r   r   r+   r,   r"   r#   r&   ÚceÚdebias_binss
             r'   Ú_ce_computer=   ?   só  € õ0 �.¥#Ñ&Ô&ð vÝœ¨¨1¨n¸qÑ.@ÈÔHYÐbmÔbtÐuÑuÔuˆàÐ&Ð&Ð&ÝÐeÐ_cÐeÐeÑfÔfÐfå	Œ‰Œð bð bÝ&8¸ÀjÐR`Ñ&aÔ&aÑ#ˆ�˜8ðbð bð bñ bô bð bð bð bð bð bð bøøøð bð bð bð bð ˆt‚|€|ÝŒy�œ 7¨XÑ#5Ñ6Ô6¸ÑAÑBÔBÐBØˆu‚}€}ÝŒY•u”y ¨8Ñ!3Ñ4Ô4Ñ5Ô5ˆØˆt‚|€|ÝŒY•u”y ¨8Ñ!3°QÑ7Ô7¸(ÑBÑCÔCˆàð 	;ð # g°¡kÑ2°XÑ=À(ÈZÏ_Ê_ÑM^ÔM^Ð_`ÔMaÑBaÐdeÑBeÑfˆKØ•%”)�EÔ,¨[Ñ9Ô9Ñ:Ô:Ñ:ˆBØ!# a¢ �uŒz˜"‰~Œ~ˆ~­U¬\¸!©_¬_Ð<Ø€Is   Á%BÂBÂBÚn_bins©r*   r.   r/   Úignore_indexc                 óî   — t          | t          ¦  «        r| dk     rt          d| › �¦  «        ‚d}||vrt          d|› d|› d�¦  «        ‚|�'t          |t          ¦  «        st          d|› �¦  «        ‚d S d S )Nr   úCExpected argument `n_bins` to be an integer larger than 0, but got r?   ú&Expected argument `norm` to be one of ú
, but got ú.úLExpected argument `ignore_index` to either be `None` or an integer, but got ©r1   r2   r4   )r>   r+   r@   Úallowed_norms       r'   Ú(_binary_calibration_error_arg_validationrI   p   s¥   € õ
 �f�cÑ"Ô"ð i f¨q¢j jÝÐgÐ_eÐgÐgÑhÔhÐhØ&€LØ�<ÐÐÝÐaÀ,ÐaÐaÐZ^ÐaÐaÐaÑbÔbÐbØÐ­
°<ÅÑ(EÔ(EÐÝÐvÐhtÐvÐvÑwÔwÐwð  ÐÐÐr)   ÚpredsÚtargetc                 ó~   — t          | ||¦  «         |                      ¦   «         st          d| j        › �¦  «        ‚d S ©NzdExpected argument `preds` to be floating tensor with probabilities/logits but got tensor with dtype )r   Úis_floating_pointr4   r   )rJ   rK   r@   s      r'   Ú+_binary_calibration_error_tensor_validationrO   ~   sZ   € õ /¨u°f¸lÑKÔKÐKØ×"Ò"Ñ$Ô$ð 
Ýð8Ø*/¬+ð8ð 8ñ
ô 
ð 	
ð
ð 
r)   c                 ó   — | |}}||fS ©N© )rJ   rK   r   r   s       r'   Ú _binary_calibration_error_updaterS   ‰   s   € Ø# V�€KØ˜
Ð"Ð"r)   é   TÚvalidate_argsc                 óÂ   — |r"t          |||¦  «         t          | ||¦  «         t          | |d|d¬¦  «        \  } }t          | |¦  «        \  }}t	          ||||¦  «        S )aZ
  `Top-label Calibration Error`_ for binary tasks.

    The expected calibration error can be used to quantify how well a given model is calibrated e.g. how well the
    predicted output probabilities of the model matches the actual probabilities of the ground truth distribution.
    Three different norms are implemented, each corresponding to variations on the calibration error metric.

    .. math::
        \text{ECE} = \sum_i^N b_i \|(p_i - c_i)\|, \text{L1 norm (Expected Calibration Error)}

    .. math::
        \text{MCE} =  \max_{i} (p_i - c_i), \text{Infinity norm (Maximum Calibration Error)}

    .. math::
        \text{RMSCE} = \sqrt{\sum_i^N b_i(p_i - c_i)^2}, \text{L2 norm (Root Mean Square Calibration Error)}

    Where :math:`p_i` is the top-1 prediction accuracy in bin :math:`i`, :math:`c_i` is the average confidence of
    predictions in bin :math:`i`, and :math:`b_i` is the fraction of data points in bin :math:`i`. Bins are constructed
    in an uniform way in the [0,1] range.

    Accepts the following input tensors:

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

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

    Args:
        preds: Tensor with predictions
        target: Tensor with true labels
        n_bins: Number of bins to use when computing the metric.
        norm: Norm used to compare empirical and expected probability bins.
        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 binary_calibration_error
        >>> preds = torch.tensor([0.25, 0.25, 0.55, 0.75, 0.75])
        >>> target = torch.tensor([0, 0, 1, 1, 1])
        >>> binary_calibration_error(preds, target, n_bins=2, norm='l1')
        tensor(0.2900)
        >>> binary_calibration_error(preds, target, n_bins=2, norm='l2')
        tensor(0.2918)
        >>> binary_calibration_error(preds, target, n_bins=2, norm='max')
        tensor(0.3167)

    g        F)Ú	thresholdr@   Úconvert_to_labels)rI   rO   r   rS   r=   )rJ   rK   r>   r+   r@   rU   r   r   s           r'   Úbinary_calibration_errorrY   Ž   s€   € ðv ð QÝ0°¸¸|ÑLÔLÐLÝ3°E¸6À<ÑPÔPÐPÝ3Øˆv °<ÐSXðñ ô �M€Eˆ6õ ?¸uÀfÑMÔMÑ€K�Ý�{ J°¸Ñ=Ô=Ð=r)   Únum_classesc                 óH  — t          | t          ¦  «        r| dk     rt          d| › �¦  «        ‚t          |t          ¦  «        r|dk     rt          d|› �¦  «        ‚d}||vrt          d|› d|› d�¦  «        ‚|�'t          |t          ¦  «        st          d	|› �¦  «        ‚d S d S )
Nr0   zHExpected argument `num_classes` to be an integer larger than 1, but got r   rB   r?   rC   rD   rE   rF   rG   )rZ   r>   r+   r@   rH   s        r'   Ú,_multiclass_calibration_error_arg_validationr\   Ó   sØ   € õ �k¥3Ñ'Ô'ð s¨;¸ª?¨?ÝÐqÐdoÐqÐqÑrÔrÐrÝ�f�cÑ"Ô"ð i f¨q¢j jÝÐgÐ_eÐgÐgÑhÔhÐhØ&€LØ�<ÐÐÝÐaÀ,ÐaÐaÐZ^ÐaÐaÐaÑbÔbÐbØÐ­
°<ÅÑ(EÔ(EÐÝÐvÐhtÐvÐvÑwÔwÐwð  ÐÐÐr)   c                 ó€   — t          | |||¦  «         |                      ¦   «         st          d| j        › �¦  «        ‚d S rM   )r
   rN   r4   r   )rJ   rK   rZ   r@   s       r'   Ú/_multiclass_calibration_error_tensor_validationr^   ä   s\   € õ 3°5¸&À+È|Ñ\Ô\Ð\Ø×"Ò"Ñ$Ô$ð 
Ýð8Ø*/¬+ð8ð 8ñ
ô 
ð 	
ð
ð 
r)   c                 óÎ   — t          | d¦  «        } |                      d¬¦  «        \  }}|                     |¦  «        }|                     ¦   «         |                     ¦   «         fS )NÚsoftmaxr   )r   )r   r/   ÚeqÚfloat)rJ   rK   r   Úpredictionsr   s        r'   Ú$_multiclass_calibration_error_updaterd   ï   s_   € õ ' u¨iÑ8Ô8€EØ$Ÿyšy¨Q˜yÑ/Ô/Ñ€K�Ø—’ Ñ'Ô'€JØ×ÒÑÔ 
× 0Ò 0Ñ 2Ô 2Ð2Ð2r)   c                 óÄ   — |r$t          ||||¦  «         t          | |||¦  «         t          | ||d¬¦  «        \  } }t          | |¦  «        \  }}t	          ||||¦  «        S )aY  `Top-label Calibration Error`_ for multiclass tasks.

    The expected calibration error can be used to quantify how well a given model is calibrated e.g. how well the
    predicted output probabilities of the model matches the actual probabilities of the ground truth distribution.
    Three different norms are implemented, each corresponding to variations on the calibration error metric.

    .. math::
        \text{ECE} = \sum_i^N b_i \|(p_i - c_i)\|, \text{L1 norm (Expected Calibration Error)}

    .. math::
        \text{MCE} =  \max_{i} (p_i - c_i), \text{Infinity norm (Maximum Calibration Error)}

    .. math::
        \text{RMSCE} = \sqrt{\sum_i^N b_i(p_i - c_i)^2}, \text{L2 norm (Root Mean Square Calibration Error)}

    Where :math:`p_i` is the top-1 prediction accuracy in bin :math:`i`, :math:`c_i` is the average confidence of
    predictions in bin :math:`i`, and :math:`b_i` is the fraction of data points in bin :math:`i`. Bins are constructed
    in an uniform way in the [0,1] range.

    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
      softmax per sample.
    - ``target`` (int tensor): ``(N, ...)``. Target should be a tensor containing ground truth labels, and therefore
      only contain values in the [0, n_classes-1] range (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_classes: Integer specifying the number of classes
        n_bins: Number of bins to use when computing the metric.
        norm: Norm used to compare empirical and expected probability bins.
        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 multiclass_calibration_error
        >>> preds = torch.tensor([[0.25, 0.20, 0.55],
        ...                       [0.55, 0.05, 0.40],
        ...                       [0.10, 0.30, 0.60],
        ...                       [0.90, 0.05, 0.05]])
        >>> target = torch.tensor([0, 1, 2, 0])
        >>> multiclass_calibration_error(preds, target, num_classes=3, n_bins=3, norm='l1')
        tensor(0.2000)
        >>> multiclass_calibration_error(preds, target, num_classes=3, n_bins=3, norm='l2')
        tensor(0.2082)
        >>> multiclass_calibration_error(preds, target, num_classes=3, n_bins=3, norm='max')
        tensor(0.2333)

    F)rX   )r\   r^   r	   rd   r=   )	rJ   rK   rZ   r>   r+   r@   rU   r   r   s	            r'   Úmulticlass_calibration_errorrf   ù   s{   € ð@ ð bÝ4°[À&È$ÐP\Ñ]Ô]Ð]Ý7¸¸vÀ{ÐT`ÑaÔaÐaÝ7¸¸vÀ|ÐglÐmÑmÔm�M€Eˆ6ÝBÀ5È&ÑQÔQÑ€K�Ý�{ J°¸Ñ=Ô=Ð=r)   Útask)ÚbinaryÚ
multiclassc           	      óR  — t          j        |¦  «        }|€J ‚|t           j        k    rt          | |||||¦  «        S |t           j        k    rJt          |t          ¦  «        s t          dt          |¦  «        › d�¦  «        ‚t          | ||||||¦  «        S t          d|› �¦  «        ‚)aœ  `Top-label Calibration Error`_.

    The expected calibration error can be used to quantify how well a given model is calibrated e.g. how well the
    predicted output probabilities of the model matches the actual probabilities of the ground truth distribution.
    Three different norms are implemented, each corresponding to variations on the calibration error metric.

    .. math::
        \text{ECE} = \sum_i^N b_i \|(p_i - c_i)\|, \text{L1 norm (Expected Calibration Error)}

    .. math::
        \text{MCE} =  \max_{i} (p_i - c_i), \text{Infinity norm (Maximum Calibration Error)}

    .. math::
        \text{RMSCE} = \sqrt{\sum_i^N b_i(p_i - c_i)^2}, \text{L2 norm (Root Mean Square Calibration Error)}

    Where :math:`p_i` is the top-1 prediction accuracy in bin :math:`i`, :math:`c_i` is the average confidence of
    predictions in bin :math:`i`, and :math:`b_i` is the fraction of data points in bin :math:`i`. Bins are constructed
    in an uniform way in the [0,1] range.

    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'`` or ``'multiclass'``. See the documentation of
    :func:`~torchmetrics.functional.classification.binary_calibration_error` and
    :func:`~torchmetrics.functional.classification.multiclass_calibration_error` for the specific details of
    each argument influence and examples.

    Nz+`num_classes` is expected to be `int` but `z was passed.`zKExpected argument `task` to either be `'binary'` or `'multiclass'` but got )
r   Úfrom_strÚBINARYrY   Ú
MULTICLASSr1   r2   r4   Útyperf   )rJ   rK   rg   r>   r+   rZ   r@   rU   s           r'   Úcalibration_errorro   A  sÃ   € õH *Ô2°4Ñ8Ô8€DØÐÐÐØÕ-Ô4Ò4Ð4Ý'¨¨v°v¸tÀ\ÐS`ÑaÔaÐaØÕ-Ô8Ò8Ð8Ý˜+¥sÑ+Ô+ð 	mÝÐkÍ4ÐP[ÑK\ÔK\ÐkÐkÐkÑlÔlÐlÝ+¨E°6¸;ÈÐPTÐVbÐdqÑrÔrÐrÝ
ÐiÐcgÐiÐiÑ
jÔ
jÐjr)   )r*   F)r*   NrQ   )rT   r*   NT)rT   r*   NNT)Útypingr   r   r   r   Útyping_extensionsr   Ú7torchmetrics.functional.classification.confusion_matrixr   r   r	   r
   Útorchmetrics.utilities.computer   Útorchmetrics.utilities.enumsr   Útupler(   r2   ÚstrÚboolr=   rI   rO   rS   rY   r\   r^   rd   rf   ro   rR   r)   r'   ú<module>rx      sÁ  ðð #Ð "Ð "Ð "Ð "Ð "Ð "Ð "à €€€Ø Ð Ð Ð Ð Ð Ø %Ð %Ð %Ð %Ð %Ð %ðð ð ð ð ð ð ð ð ð ð ð ð FÐ EÐ EÐ EÐ EÐ EØ GÐ GÐ GÐ GÐ GÐ Gð'Øð'Ø%+ð'Ø=Cð'à
ˆ6�6˜6Ð!Ô"ð'ð 'ð 'ð 'ðJ Øð.ð .Øð.àð.ð ˜& #˜+Ô&ð.ð ð	.ð
 ð.ð ð.ð .ð .ð .ðf (,Ø"&ðxð xØðxà
Ð#Ô
$ðxð ˜3”-ðxð 
ð	xð xð xð xð BFð
ð 
Øð
Ø!ð
Ø19¸#´ð
à	ð
ð 
ð 
ð 
ð#¨Fð #¸Fð #ÀuÈVÐU[È^ÔG\ð #ð #ð #ð #ð Ø'+Ø"&ØðB>ð B>ØðB>àðB>ð ðB>ð Ð#Ô
$ð	B>ð
 ˜3”-ðB>ð ðB>ð ðB>ð B>ð B>ð B>ðP (,Ø"&ð	xð xØðxàðxð Ð#Ô
$ðxð ˜3”-ð	xð
 
ðxð xð xð xð$ TXð
ð 
Øð
Ø!ð
Ø03ð
ØCKÈCÄ=ð
à	ð
ð 
ð 
ð 
ð3Øð3àð3ð ˆ6�6ˆ>Ôð3ð 3ð 3ð 3ð Ø'+Ø"&ØðE>ð E>ØðE>àðE>ð ðE>ð ð	E>ð
 Ð#Ô
$ðE>ð ˜3”-ðE>ð ðE>ð ðE>ð E>ð E>ð E>ðX Ø'+Ø!%Ø"&Øð,kð ,kØð,kàð,kð Ð(Ô
)ð,kð ð	,kð
 Ð#Ô
$ð,kð ˜#”ð,kð ˜3”-ð,kð ð,kð ð,kð ,kð ,kð ,kð ,kð ,kr)   