o
    yi1                     @   s   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mZmZmZmZmZ d dlmZ d dlmZ G dd	 d	eZG d
d deZG dd dZdS )    )AnyOptionalN)Tensor)Literal)	(_binary_calibration_error_arg_validation+_binary_calibration_error_tensor_validation _binary_calibration_error_update_binary_confusion_matrix_format_ce_compute,_multiclass_calibration_error_arg_validation/_multiclass_calibration_error_tensor_validation$_multiclass_calibration_error_update#_multiclass_confusion_matrix_format)Metric)dim_zero_catc                       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
d 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 )BinaryCalibrationErrora  `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.

    As input to ``forward`` and ``update`` the metric accepts the following input:

    - ``preds`` (:class:`~torch.Tensor`): A float tensor of shape ``(N, ...)`` 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, ...)`` 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.

    As output to ``forward`` and ``compute`` the metric returns the following output:

    - ``bce`` (:class:`~torch.Tensor`): A scalar tensor containing the calibration error

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

    Args:
        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.
        kwargs: Additional keyword arguments, see :ref:`Metric kwargs` for more info.

    Example:
        >>> from torchmetrics.classification import BinaryCalibrationError
        >>> preds = torch.tensor([0.25, 0.25, 0.55, 0.75, 0.75])
        >>> target = torch.tensor([0, 0, 1, 1, 1])
        >>> metric = BinaryCalibrationError(n_bins=2, norm='l1')
        >>> metric(preds, target)
        tensor(0.2900)
        >>> bce = BinaryCalibrationError(n_bins=2, norm='l2')
        >>> bce(preds, target)
        tensor(0.2918)
        >>> bce = BinaryCalibrationError(n_bins=2, norm='max')
        >>> bce(preds, target)
        tensor(0.3167)
    Fis_differentiablehigher_is_betterfull_state_update   l1NTn_binsnormr   l2maxignore_indexvalidate_argskwargsreturnc                    s^   t  jdi | |rt||| || _|| _|| _|| _| jdg dd | jdg dd d S Nconfidencescat)dist_reduce_fx
accuracies )super__init__r   r   r   r   r   	add_state)selfr   r   r   r   r   	__class__r%   a/home/ubuntu/.local/lib/python3.10/site-packages/torchmetrics/classification/calibration_error.pyr'   a   s   zBinaryCalibrationError.__init__predstargetc                 C   sV   | j r
t||| j t||d| jdd\}}t||\}}| j| | j| d S )Ng        F)	thresholdr   convert_to_labels)r   r   r   r	   r   r!   appendr$   r)   r-   r.   r!   r$   r%   r%   r,   updates   s   
zBinaryCalibrationError.updatec                 C   (   t | j}t | j}t||| j| jdS N)r   r   r!   r$   r
   r   r   r)   r!   r$   r%   r%   r,   compute}      

zBinaryCalibrationError.computer   r   NT__name__
__module____qualname____doc__r   bool__annotations__r   r   intr   r   r   r'   r   r3   r8   __classcell__r%   r%   r*   r,   r   #   s0   
 9
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	de
d 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 )MulticlassCalibrationErrora  `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.

    As input to ``forward`` and ``update`` the metric accepts the following input:

    - ``preds`` (:class:`~torch.Tensor`): A float tensor of shape ``(N, C, ...)`` 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`` (:class:`~torch.Tensor`): An int tensor of shape ``(N, ...)`` containing ground truth labels, and
      therefore only contain values in the [0, n_classes-1] range (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:

    - ``mcce`` (:class:`~torch.Tensor`): A scalar tensor containing the calibration error

    Args:
        num_classes: Integer specifing 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.
        kwargs: Additional keyword arguments, see :ref:`Metric kwargs` for more info.

    Example:
        >>> from torchmetrics.classification import MulticlassCalibrationError
        >>> 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])
        >>> metric = MulticlassCalibrationError(num_classes=3, n_bins=3, norm='l1')
        >>> metric(preds, target)
        tensor(0.2000)
        >>> mcce = MulticlassCalibrationError(num_classes=3, n_bins=3, norm='l2')
        >>> mcce(preds, target)
        tensor(0.2082)
        >>> mcce = MulticlassCalibrationError(num_classes=3, n_bins=3, norm='max')
        >>> mcce(preds, target)
        tensor(0.2333)
    Fr   r   r   r   r   NTnum_classesr   r   r   r   r   r   r   c                    sf   t  jdi | |rt|||| || _|| _|| _|| _|| _| jdg dd | jdg dd d S r    )	r&   r'   r   r   rE   r   r   r   r(   )r)   rE   r   r   r   r   r   r*   r%   r,   r'      s   	z#MulticlassCalibrationError.__init__r-   r.   c                 C   sX   | j rt||| j| j t||| jdd\}}t||\}}| j| | j| d S )NF)r   r0   )	r   r   rE   r   r   r   r!   r1   r$   r2   r%   r%   r,   r3      s   

z!MulticlassCalibrationError.updatec                 C   r4   r5   r6   r7   r%   r%   r,   r8      r9   z"MulticlassCalibrationError.computer:   r;   r%   r%   r*   r,   rD      s4   
 =
rD   c                   @   sX   e Zd ZdZ						dded ded	ed
 dee dee dedede	fddZ
dS )CalibrationErroraA  `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
    :mod:`BinaryCalibrationError` and :mod:`MulticlassCalibrationError` for the specific details of
    each argument influence and examples.
    Nr   r   Ttask)binary
multiclassr   r   r   rE   r   r   r   r   c                 K   s`   | t||||d |dkrtdi |S |dkr)t|ts!J t|fi |S td| )N)r   r   r   r   rH   rI   z[Expected argument `task` to either be `'binary'`, `'multiclass'` or `'multilabel'` but got r%   )r3   dictr   
isinstancerB   rD   
ValueError)clsrG   r   r   rE   r   r   r   r%   r%   r,   __new__  s   
zCalibrationError.__new__)Nr   r   NNT)r<   r=   r>   r?   r   rB   r   r@   r   r   rN   r%   r%   r%   r,   rF      s2    	rF   )typingr   r   torchr   typing_extensionsr   8torchmetrics.functional.classification.calibration_errorr   r   r   r	   r
   r   r   r   r   torchmetrics.metricr   torchmetrics.utilities.datar   r   rD   rF   r%   r%   r%   r,   <module>   s   ,`f