calibration_error.py 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392
  1. # Copyright The Lightning team.
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. from collections.abc import Sequence
  15. from typing import Any, List, Optional, Union
  16. from torch import Tensor
  17. from typing_extensions import Literal
  18. from torchmetrics.classification.base import _ClassificationTaskWrapper
  19. from torchmetrics.functional.classification.calibration_error import (
  20. _binary_calibration_error_arg_validation,
  21. _binary_calibration_error_tensor_validation,
  22. _binary_calibration_error_update,
  23. _binary_confusion_matrix_format,
  24. _ce_compute,
  25. _multiclass_calibration_error_arg_validation,
  26. _multiclass_calibration_error_tensor_validation,
  27. _multiclass_calibration_error_update,
  28. _multiclass_confusion_matrix_format,
  29. )
  30. from torchmetrics.metric import Metric
  31. from torchmetrics.utilities.data import dim_zero_cat
  32. from torchmetrics.utilities.enums import ClassificationTaskNoMultilabel
  33. from torchmetrics.utilities.imports import _MATPLOTLIB_AVAILABLE
  34. from torchmetrics.utilities.plot import _AX_TYPE, _PLOT_OUT_TYPE
  35. if not _MATPLOTLIB_AVAILABLE:
  36. __doctest_skip__ = ["BinaryCalibrationError.plot", "MulticlassCalibrationError.plot"]
  37. class BinaryCalibrationError(Metric):
  38. r"""`Top-label Calibration Error`_ for binary tasks.
  39. The expected calibration error can be used to quantify how well a given model is calibrated e.g. how well the
  40. predicted output probabilities of the model matches the actual probabilities of the ground truth distribution.
  41. Three different norms are implemented, each corresponding to variations on the calibration error metric.
  42. .. math::
  43. \text{ECE} = \sum_i^N b_i \|(p_i - c_i)\|, \text{L1 norm (Expected Calibration Error)}
  44. .. math::
  45. \text{MCE} = \max_{i} (p_i - c_i), \text{Infinity norm (Maximum Calibration Error)}
  46. .. math::
  47. \text{RMSCE} = \sqrt{\sum_i^N b_i(p_i - c_i)^2}, \text{L2 norm (Root Mean Square Calibration Error)}
  48. Where :math:`p_i` is the top-1 prediction accuracy in bin :math:`i`, :math:`c_i` is the average confidence of
  49. predictions in bin :math:`i`, and :math:`b_i` is the fraction of data points in bin :math:`i`. Bins are constructed
  50. in an uniform way in the [0,1] range.
  51. As input to ``forward`` and ``update`` the metric accepts the following input:
  52. - ``preds`` (:class:`~torch.Tensor`): A float tensor of shape ``(N, ...)`` containing probabilities or logits for
  53. each observation. If preds has values outside [0,1] range we consider the input to be logits and will auto apply
  54. sigmoid per element.
  55. - ``target`` (:class:`~torch.Tensor`): An int tensor of shape ``(N, ...)`` containing ground truth labels, and
  56. therefore only contain {0,1} values (except if `ignore_index` is specified). The value 1 always encodes the
  57. positive class.
  58. As output to ``forward`` and ``compute`` the metric returns the following output:
  59. - ``bce`` (:class:`~torch.Tensor`): A scalar tensor containing the calibration error
  60. Additional dimension ``...`` will be flattened into the batch dimension.
  61. Args:
  62. n_bins: Number of bins to use when computing the metric.
  63. norm: Norm used to compare empirical and expected probability bins.
  64. ignore_index:
  65. Specifies a target value that is ignored and does not contribute to the metric calculation
  66. validate_args: bool indicating if input arguments and tensors should be validated for correctness.
  67. Set to ``False`` for faster computations.
  68. kwargs: Additional keyword arguments, see :ref:`Metric kwargs` for more info.
  69. Example:
  70. >>> from torch import tensor
  71. >>> from torchmetrics.classification import BinaryCalibrationError
  72. >>> preds = tensor([0.25, 0.25, 0.55, 0.75, 0.75])
  73. >>> target = tensor([0, 0, 1, 1, 1])
  74. >>> metric = BinaryCalibrationError(n_bins=2, norm='l1')
  75. >>> metric(preds, target)
  76. tensor(0.2900)
  77. >>> bce = BinaryCalibrationError(n_bins=2, norm='l2')
  78. >>> bce(preds, target)
  79. tensor(0.2918)
  80. >>> bce = BinaryCalibrationError(n_bins=2, norm='max')
  81. >>> bce(preds, target)
  82. tensor(0.3167)
  83. """
  84. is_differentiable: bool = False
  85. higher_is_better: bool = False
  86. full_state_update: bool = False
  87. plot_lower_bound: float = 0.0
  88. plot_upper_bound: float = 1.0
  89. confidences: List[Tensor]
  90. accuracies: List[Tensor]
  91. def __init__(
  92. self,
  93. n_bins: int = 15,
  94. norm: Literal["l1", "l2", "max"] = "l1",
  95. ignore_index: Optional[int] = None,
  96. validate_args: bool = True,
  97. **kwargs: Any,
  98. ) -> None:
  99. super().__init__(**kwargs)
  100. if validate_args:
  101. _binary_calibration_error_arg_validation(n_bins, norm, ignore_index)
  102. self.validate_args = validate_args
  103. self.n_bins = n_bins
  104. self.norm = norm
  105. self.ignore_index = ignore_index
  106. self.add_state("confidences", [], dist_reduce_fx="cat")
  107. self.add_state("accuracies", [], dist_reduce_fx="cat")
  108. def update(self, preds: Tensor, target: Tensor) -> None:
  109. """Update metric states with predictions and targets."""
  110. if self.validate_args:
  111. _binary_calibration_error_tensor_validation(preds, target, self.ignore_index)
  112. preds, target = _binary_confusion_matrix_format(
  113. preds, target, threshold=0.0, ignore_index=self.ignore_index, convert_to_labels=False
  114. )
  115. confidences, accuracies = _binary_calibration_error_update(preds, target)
  116. self.confidences.append(confidences)
  117. self.accuracies.append(accuracies)
  118. def compute(self) -> Tensor:
  119. """Compute metric."""
  120. confidences = dim_zero_cat(self.confidences)
  121. accuracies = dim_zero_cat(self.accuracies)
  122. return _ce_compute(confidences, accuracies, self.n_bins, norm=self.norm)
  123. def plot(
  124. self, val: Optional[Union[Tensor, Sequence[Tensor]]] = None, ax: Optional[_AX_TYPE] = None
  125. ) -> _PLOT_OUT_TYPE:
  126. """Plot a single or multiple values from the metric.
  127. Args:
  128. val: Either a single result from calling `metric.forward` or `metric.compute` or a list of these results.
  129. If no value is provided, will automatically call `metric.compute` and plot that result.
  130. ax: An matplotlib axis object. If provided will add plot to that axis
  131. Returns:
  132. Figure object and Axes object
  133. Raises:
  134. ModuleNotFoundError:
  135. If `matplotlib` is not installed
  136. .. plot::
  137. :scale: 75
  138. >>> from torch import rand, randint
  139. >>> # Example plotting a single value
  140. >>> from torchmetrics.classification import BinaryCalibrationError
  141. >>> metric = BinaryCalibrationError(n_bins=2, norm='l1')
  142. >>> metric.update(rand(10), randint(2,(10,)))
  143. >>> fig_, ax_ = metric.plot()
  144. .. plot::
  145. :scale: 75
  146. >>> from torch import rand, randint
  147. >>> # Example plotting multiple values
  148. >>> from torchmetrics.classification import BinaryCalibrationError
  149. >>> metric = BinaryCalibrationError(n_bins=2, norm='l1')
  150. >>> values = [ ]
  151. >>> for _ in range(10):
  152. ... values.append(metric(rand(10), randint(2,(10,))))
  153. >>> fig_, ax_ = metric.plot(values)
  154. """
  155. return self._plot(val, ax)
  156. class MulticlassCalibrationError(Metric):
  157. r"""`Top-label Calibration Error`_ for multiclass tasks.
  158. The expected calibration error can be used to quantify how well a given model is calibrated e.g. how well the
  159. predicted output probabilities of the model matches the actual probabilities of the ground truth distribution.
  160. Three different norms are implemented, each corresponding to variations on the calibration error metric.
  161. .. math::
  162. \text{ECE} = \sum_i^N b_i \|(p_i - c_i)\|, \text{L1 norm (Expected Calibration Error)}
  163. .. math::
  164. \text{MCE} = \max_{i} (p_i - c_i), \text{Infinity norm (Maximum Calibration Error)}
  165. .. math::
  166. \text{RMSCE} = \sqrt{\sum_i^N b_i(p_i - c_i)^2}, \text{L2 norm (Root Mean Square Calibration Error)}
  167. Where :math:`p_i` is the top-1 prediction accuracy in bin :math:`i`, :math:`c_i` is the average confidence of
  168. predictions in bin :math:`i`, and :math:`b_i` is the fraction of data points in bin :math:`i`. Bins are constructed
  169. in an uniform way in the [0,1] range.
  170. As input to ``forward`` and ``update`` the metric accepts the following input:
  171. - ``preds`` (:class:`~torch.Tensor`): A float tensor of shape ``(N, C, ...)`` containing probabilities or logits for
  172. each observation. If preds has values outside [0,1] range we consider the input to be logits and will auto apply
  173. softmax per sample.
  174. - ``target`` (:class:`~torch.Tensor`): An int tensor of shape ``(N, ...)`` containing ground truth labels, and
  175. therefore only contain values in the [0, n_classes-1] range (except if `ignore_index` is specified).
  176. .. tip::
  177. Additional dimension ``...`` will be flattened into the batch dimension.
  178. As output to ``forward`` and ``compute`` the metric returns the following output:
  179. - ``mcce`` (:class:`~torch.Tensor`): A scalar tensor containing the calibration error
  180. Args:
  181. num_classes: Integer specifying the number of classes
  182. n_bins: Number of bins to use when computing the metric.
  183. norm: Norm used to compare empirical and expected probability bins.
  184. ignore_index:
  185. Specifies a target value that is ignored and does not contribute to the metric calculation
  186. validate_args: bool indicating if input arguments and tensors should be validated for correctness.
  187. Set to ``False`` for faster computations.
  188. kwargs: Additional keyword arguments, see :ref:`Metric kwargs` for more info.
  189. Example:
  190. >>> from torch import tensor
  191. >>> from torchmetrics.classification import MulticlassCalibrationError
  192. >>> preds = tensor([[0.25, 0.20, 0.55],
  193. ... [0.55, 0.05, 0.40],
  194. ... [0.10, 0.30, 0.60],
  195. ... [0.90, 0.05, 0.05]])
  196. >>> target = tensor([0, 1, 2, 0])
  197. >>> metric = MulticlassCalibrationError(num_classes=3, n_bins=3, norm='l1')
  198. >>> metric(preds, target)
  199. tensor(0.2000)
  200. >>> mcce = MulticlassCalibrationError(num_classes=3, n_bins=3, norm='l2')
  201. >>> mcce(preds, target)
  202. tensor(0.2082)
  203. >>> mcce = MulticlassCalibrationError(num_classes=3, n_bins=3, norm='max')
  204. >>> mcce(preds, target)
  205. tensor(0.2333)
  206. """
  207. is_differentiable: bool = False
  208. higher_is_better: bool = False
  209. full_state_update: bool = False
  210. plot_lower_bound: float = 0.0
  211. plot_upper_bound: float = 1.0
  212. plot_legend_name: str = "Class"
  213. confidences: List[Tensor]
  214. accuracies: List[Tensor]
  215. def __init__(
  216. self,
  217. num_classes: int,
  218. n_bins: int = 15,
  219. norm: Literal["l1", "l2", "max"] = "l1",
  220. ignore_index: Optional[int] = None,
  221. validate_args: bool = True,
  222. **kwargs: Any,
  223. ) -> None:
  224. super().__init__(**kwargs)
  225. if validate_args:
  226. _multiclass_calibration_error_arg_validation(num_classes, n_bins, norm, ignore_index)
  227. self.validate_args = validate_args
  228. self.num_classes = num_classes
  229. self.n_bins = n_bins
  230. self.norm = norm
  231. self.ignore_index = ignore_index
  232. self.add_state("confidences", [], dist_reduce_fx="cat")
  233. self.add_state("accuracies", [], dist_reduce_fx="cat")
  234. def update(self, preds: Tensor, target: Tensor) -> None:
  235. """Update metric states with predictions and targets."""
  236. if self.validate_args:
  237. _multiclass_calibration_error_tensor_validation(preds, target, self.num_classes, self.ignore_index)
  238. preds, target = _multiclass_confusion_matrix_format(
  239. preds, target, ignore_index=self.ignore_index, convert_to_labels=False
  240. )
  241. confidences, accuracies = _multiclass_calibration_error_update(preds, target)
  242. self.confidences.append(confidences)
  243. self.accuracies.append(accuracies)
  244. def compute(self) -> Tensor:
  245. """Compute metric."""
  246. confidences = dim_zero_cat(self.confidences)
  247. accuracies = dim_zero_cat(self.accuracies)
  248. return _ce_compute(confidences, accuracies, self.n_bins, norm=self.norm)
  249. def plot(
  250. self, val: Optional[Union[Tensor, Sequence[Tensor]]] = None, ax: Optional[_AX_TYPE] = None
  251. ) -> _PLOT_OUT_TYPE:
  252. """Plot a single or multiple values from the metric.
  253. Args:
  254. val: Either a single result from calling `metric.forward` or `metric.compute` or a list of these results.
  255. If no value is provided, will automatically call `metric.compute` and plot that result.
  256. ax: An matplotlib axis object. If provided will add plot to that axis
  257. Returns:
  258. Figure object and Axes object
  259. Raises:
  260. ModuleNotFoundError:
  261. If `matplotlib` is not installed
  262. .. plot::
  263. :scale: 75
  264. >>> from torch import randn, randint
  265. >>> # Example plotting a single value
  266. >>> from torchmetrics.classification import MulticlassCalibrationError
  267. >>> metric = MulticlassCalibrationError(num_classes=3, n_bins=3, norm='l1')
  268. >>> metric.update(randn(20,3).softmax(dim=-1), randint(3, (20,)))
  269. >>> fig_, ax_ = metric.plot()
  270. .. plot::
  271. :scale: 75
  272. >>> from torch import randn, randint
  273. >>> # Example plotting a multiple values
  274. >>> from torchmetrics.classification import MulticlassCalibrationError
  275. >>> metric = MulticlassCalibrationError(num_classes=3, n_bins=3, norm='l1')
  276. >>> values = []
  277. >>> for _ in range(20):
  278. ... values.append(metric(randn(20,3).softmax(dim=-1), randint(3, (20,))))
  279. >>> fig_, ax_ = metric.plot(values)
  280. """
  281. return self._plot(val, ax)
  282. class CalibrationError(_ClassificationTaskWrapper):
  283. r"""`Top-label Calibration Error`_.
  284. The expected calibration error can be used to quantify how well a given model is calibrated e.g. how well the
  285. predicted output probabilities of the model matches the actual probabilities of the ground truth distribution.
  286. Three different norms are implemented, each corresponding to variations on the calibration error metric.
  287. .. math::
  288. \text{ECE} = \sum_i^N b_i \|(p_i - c_i)\|, \text{L1 norm (Expected Calibration Error)}
  289. .. math::
  290. \text{MCE} = \max_{i} (p_i - c_i), \text{Infinity norm (Maximum Calibration Error)}
  291. .. math::
  292. \text{RMSCE} = \sqrt{\sum_i^N b_i(p_i - c_i)^2}, \text{L2 norm (Root Mean Square Calibration Error)}
  293. Where :math:`p_i` is the top-1 prediction accuracy in bin :math:`i`, :math:`c_i` is the average confidence of
  294. predictions in bin :math:`i`, and :math:`b_i` is the fraction of data points in bin :math:`i`. Bins are constructed
  295. in an uniform way in the [0,1] range.
  296. This function is a simple wrapper to get the task specific versions of this metric, which is done by setting the
  297. ``task`` argument to either ``'binary'`` or ``'multiclass'``. See the documentation of
  298. :class:`~torchmetrics.classification.BinaryCalibrationError` and
  299. :class:`~torchmetrics.classification.MulticlassCalibrationError` for the specific details of each argument influence
  300. and examples.
  301. """
  302. def __new__( # type: ignore[misc]
  303. cls: type["CalibrationError"],
  304. task: Literal["binary", "multiclass"],
  305. n_bins: int = 15,
  306. norm: Literal["l1", "l2", "max"] = "l1",
  307. num_classes: Optional[int] = None,
  308. ignore_index: Optional[int] = None,
  309. validate_args: bool = True,
  310. **kwargs: Any,
  311. ) -> Metric:
  312. """Initialize task metric."""
  313. task = ClassificationTaskNoMultilabel.from_str(task)
  314. kwargs.update({"n_bins": n_bins, "norm": norm, "ignore_index": ignore_index, "validate_args": validate_args})
  315. if task == ClassificationTaskNoMultilabel.BINARY:
  316. return BinaryCalibrationError(**kwargs)
  317. if task == ClassificationTaskNoMultilabel.MULTICLASS:
  318. if not isinstance(num_classes, int):
  319. raise ValueError(f"`num_classes` is expected to be `int` but `{type(num_classes)} was passed.`")
  320. return MulticlassCalibrationError(num_classes, **kwargs)
  321. raise ValueError(f"Not handled value: {task}")