o
    .wiC                     @   s   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 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 d d	lmZ d d
lmZ d dlm Z m!Z! es`ddgZ"G dd deZ#G dd deZ$G dd deZ%dS )    )Sequence)AnyListOptionalUnion)Tensor)Literal)_ClassificationTaskWrapper)	(_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_cat)ClassificationTaskNoMultilabel)_MATPLOTLIB_AVAILABLE)_AX_TYPE_PLOT_OUT_TYPEBinaryCalibrationError.plotMulticlassCalibrationError.plotc                       s   e Zd ZU dZdZeed< dZeed< dZeed< dZ	e
ed< dZe
ed	< ee ed
< e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	d$deeeee f  d ee 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 torch import tensor
        >>> from torchmetrics.classification import BinaryCalibrationError
        >>> preds = tensor([0.25, 0.25, 0.55, 0.75, 0.75])
        >>> target = 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        plot_lower_bound      ?plot_upper_boundconfidences
accuracies   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 Nr#   cat)dist_reduce_fxr$    )super__init__r
   r-   r'   r(   r,   	add_state)selfr'   r(   r,   r-   r.   	__class__r3   j/home/ubuntu/sommelier/.venv/lib/python3.10/site-packages/torchmetrics/classification/calibration_error.pyr5   p   s   zBinaryCalibrationError.__init__predstargetc                 C   sV   | j r
t||| j t||d| jdd\}}t||\}}| j| | j| dS )2Update metric states with predictions and targets.r   F)	thresholdr,   convert_to_labelsN)r-   r   r,   r   r   r#   appendr$   r7   r;   r<   r#   r$   r3   r3   r:   update   s   
zBinaryCalibrationError.updatec                 C   (   t | j}t | j}t||| j| jdS zCompute metric.)r(   r   r#   r$   r   r'   r(   r7   r#   r$   r3   r3   r:   compute      

zBinaryCalibrationError.computevalaxc                 C      |  ||S )aw  Plot a single or multiple values from the metric.

        Args:
            val: Either a single result from calling `metric.forward` or `metric.compute` or a list of these results.
                If no value is provided, will automatically call `metric.compute` and plot that result.
            ax: An matplotlib axis object. If provided will add plot to that axis

        Returns:
            Figure object and Axes object

        Raises:
            ModuleNotFoundError:
                If `matplotlib` is not installed

        .. plot::
            :scale: 75

            >>> from torch import rand, randint
            >>> # Example plotting a single value
            >>> from torchmetrics.classification import BinaryCalibrationError
            >>> metric = BinaryCalibrationError(n_bins=2, norm='l1')
            >>> metric.update(rand(10), randint(2,(10,)))
            >>> fig_, ax_ = metric.plot()

        .. plot::
            :scale: 75

            >>> from torch import rand, randint
            >>> # Example plotting multiple values
            >>> from torchmetrics.classification import BinaryCalibrationError
            >>> metric = BinaryCalibrationError(n_bins=2, norm='l1')
            >>> values = [ ]
            >>> for _ in range(10):
            ...     values.append(metric(rand(10), randint(2,(10,))))
            >>> fig_, ax_ = metric.plot(values)

        _plotr7   rI   rJ   r3   r3   r:   plot      (r   r%   r&   NTNN)__name__
__module____qualname____doc__r   bool__annotations__r   r   r    floatr"   r   r   intr   r   r   r5   rB   rG   r   r   r   r   rO   __classcell__r3   r3   r8   r:   r   *   sH   
 <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Z	e
ed< dZe
ed	< d
Zeed< ee ed< e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	d'd"eeeee f  d#ee 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).

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

    Example:
        >>> from torch import tensor
        >>> from torchmetrics.classification import MulticlassCalibrationError
        >>> preds = 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 = 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    r!   r"   Classplot_legend_namer#   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 r0   )	r4   r5   r   r-   r_   r'   r(   r,   r6   )r7   r_   r'   r(   r,   r-   r.   r8   r3   r:   r5   	  s   	z#MulticlassCalibrationError.__init__r;   r<   c                 C   sX   | j rt||| j| j t||| jdd\}}t||\}}| j| | j| dS )r=   F)r,   r?   N)	r-   r   r_   r,   r   r   r#   r@   r$   rA   r3   r3   r:   rB     s   

z!MulticlassCalibrationError.updatec                 C   rC   rD   rE   rF   r3   r3   r:   rG   (  rH   z"MulticlassCalibrationError.computerI   rJ   c                 C   rK   )a  Plot a single or multiple values from the metric.

        Args:
            val: Either a single result from calling `metric.forward` or `metric.compute` or a list of these results.
                If no value is provided, will automatically call `metric.compute` and plot that result.
            ax: An matplotlib axis object. If provided will add plot to that axis

        Returns:
            Figure object and Axes object

        Raises:
            ModuleNotFoundError:
                If `matplotlib` is not installed

        .. plot::
            :scale: 75

            >>> from torch import randn, randint
            >>> # Example plotting a single value
            >>> from torchmetrics.classification import MulticlassCalibrationError
            >>> metric = MulticlassCalibrationError(num_classes=3, n_bins=3, norm='l1')
            >>> metric.update(randn(20,3).softmax(dim=-1), randint(3, (20,)))
            >>> fig_, ax_ = metric.plot()

        .. plot::
            :scale: 75

            >>> from torch import randn, randint
            >>> # Example plotting a multiple values
            >>> from torchmetrics.classification import MulticlassCalibrationError
            >>> metric = MulticlassCalibrationError(num_classes=3, n_bins=3, norm='l1')
            >>> values = []
            >>> for _ in range(20):
            ...     values.append(metric(randn(20,3).softmax(dim=-1), randint(3, (20,))))
            >>> fig_, ax_ = metric.plot(values)

        rL   rN   r3   r3   r:   rO   .  rP   r   rQ   rR   )rS   rT   rU   rV   r   rW   rX   r   r   r    rY   r"   r^   strr   r   rZ   r   r   r   r5   rB   rG   r   r   r   r   rO   r[   r3   r3   r8   r:   r\      sN   
 @r\   c                   @   s^   e Zd ZdZ					dde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 )CalibrationErrora  `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
    :class:`~torchmetrics.classification.BinaryCalibrationError` and
    :class:`~torchmetrics.classification.MulticlassCalibrationError` for the specific details of each argument influence
    and examples.

    r%   r&   NTclstask)binary
multiclassr'   r(   r)   r_   r,   r-   r.   r/   c                 K   s|   t |}|||||d |t jkrtdi |S |t jkr7t|ts/tdt	| dt
|fi |S td| )zInitialize task metric.)r'   r(   r,   r-   z+`num_classes` is expected to be `int` but `z was passed.`zNot handled value: Nr3   )r   from_strrB   BINARYr   
MULTICLASS
isinstancerZ   
ValueErrortyper\   )rb   rc   r'   r(   r_   r,   r-   r.   r3   r3   r:   __new__u  s   



zCalibrationError.__new__)r%   r&   NNT)rS   rT   rU   rV   rk   r   rZ   r   rW   r   r   rl   r3   r3   r3   r:   ra   Y  s4    	ra   N)&collections.abcr   typingr   r   r   r   torchr   typing_extensionsr    torchmetrics.classification.baser	   8torchmetrics.functional.classification.calibration_errorr
   r   r   r   r   r   r   r   r   torchmetrics.metricr   torchmetrics.utilities.datar   torchmetrics.utilities.enumsr   torchmetrics.utilities.importsr   torchmetrics.utilities.plotr   r   __doctest_skip__r   r\   ra   r3   r3   r3   r:   <module>   s$   ,  