minkowski.py 4.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122
  1. # Copyright The PyTorch 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, Optional, Union
  16. from torch import Tensor, tensor
  17. from torchmetrics.functional.regression.minkowski import _minkowski_distance_compute, _minkowski_distance_update
  18. from torchmetrics.metric import Metric
  19. from torchmetrics.utilities.exceptions import TorchMetricsUserError
  20. from torchmetrics.utilities.imports import _MATPLOTLIB_AVAILABLE
  21. from torchmetrics.utilities.plot import _AX_TYPE, _PLOT_OUT_TYPE
  22. if not _MATPLOTLIB_AVAILABLE:
  23. __doctest_skip__ = ["MinkowskiDistance.plot"]
  24. class MinkowskiDistance(Metric):
  25. r"""Compute `Minkowski Distance`_.
  26. .. math::
  27. d_{\text{Minkowski}} = \sum_{i}^N (| y_i - \hat{y_i} |^p)^\frac{1}{p}
  28. where
  29. :math: `y` is a tensor of target values,
  30. :math: `\hat{y}` is a tensor of predictions,
  31. :math: `\p` is a non-negative integer or floating-point number
  32. This metric can be seen as generalized version of the standard euclidean distance which corresponds to minkowski
  33. distance with p=2.
  34. Args:
  35. p: int or float larger than 1, exponent to which the difference between preds and target is to be raised
  36. kwargs: Additional keyword arguments, see :ref:`Metric kwargs` for more info.
  37. Example:
  38. >>> from torchmetrics.regression import MinkowskiDistance
  39. >>> target = tensor([1.0, 2.8, 3.5, 4.5])
  40. >>> preds = tensor([6.1, 2.11, 3.1, 5.6])
  41. >>> minkowski_distance = MinkowskiDistance(3)
  42. >>> minkowski_distance(preds, target)
  43. tensor(5.1220)
  44. """
  45. is_differentiable: Optional[bool] = True
  46. higher_is_better: Optional[bool] = False
  47. full_state_update: Optional[bool] = False
  48. plot_lower_bound: float = 0.0
  49. minkowski_dist_sum: Tensor
  50. def __init__(self, p: float, **kwargs: Any) -> None:
  51. super().__init__(**kwargs)
  52. if not (isinstance(p, (float, int)) and p >= 1):
  53. raise TorchMetricsUserError(f"Argument ``p`` must be a float or int greater than 1, but got {p}")
  54. self.p = p
  55. self.add_state("minkowski_dist_sum", default=tensor(0.0), dist_reduce_fx="sum")
  56. def update(self, preds: Tensor, targets: Tensor) -> None:
  57. """Update state with predictions and targets."""
  58. minkowski_dist_sum = _minkowski_distance_update(preds, targets, self.p)
  59. self.minkowski_dist_sum += minkowski_dist_sum
  60. def compute(self) -> Tensor:
  61. """Compute metric."""
  62. return _minkowski_distance_compute(self.minkowski_dist_sum, self.p)
  63. def plot(
  64. self, val: Optional[Union[Tensor, Sequence[Tensor]]] = None, ax: Optional[_AX_TYPE] = None
  65. ) -> _PLOT_OUT_TYPE:
  66. """Plot a single or multiple values from the metric.
  67. Args:
  68. val: Either a single result from calling `metric.forward` or `metric.compute` or a list of these results.
  69. If no value is provided, will automatically call `metric.compute` and plot that result.
  70. ax: An matplotlib axis object. If provided will add plot to that axis
  71. Returns:
  72. Figure and Axes object
  73. Raises:
  74. ModuleNotFoundError:
  75. If `matplotlib` is not installed
  76. .. plot::
  77. :scale: 75
  78. >>> from torch import randn
  79. >>> # Example plotting a single value
  80. >>> from torchmetrics.regression import MinkowskiDistance
  81. >>> metric = MinkowskiDistance(p=3)
  82. >>> metric.update(randn(10,), randn(10,))
  83. >>> fig_, ax_ = metric.plot()
  84. .. plot::
  85. :scale: 75
  86. >>> from torch import randn
  87. >>> # Example plotting multiple values
  88. >>> from torchmetrics.regression import MinkowskiDistance
  89. >>> metric = MinkowskiDistance(p=3)
  90. >>> values = []
  91. >>> for _ in range(10):
  92. ... values.append(metric(randn(10,), randn(10,)))
  93. >>> fig, ax = metric.plot(values)
  94. """
  95. return self._plot(val, ax)