edit.py 7.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175
  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, Literal, Optional, Union
  16. import torch
  17. from torch import Tensor
  18. from torchmetrics.functional.text.edit import _edit_distance_compute, _edit_distance_update
  19. from torchmetrics.metric import Metric
  20. from torchmetrics.utilities.data import dim_zero_cat
  21. from torchmetrics.utilities.imports import _MATPLOTLIB_AVAILABLE
  22. from torchmetrics.utilities.plot import _AX_TYPE, _PLOT_OUT_TYPE
  23. if not _MATPLOTLIB_AVAILABLE:
  24. __doctest_skip__ = ["EditDistance.plot"]
  25. class EditDistance(Metric):
  26. """Calculates the Levenshtein edit distance between two sequences.
  27. The edit distance is the number of characters that need to be substituted, inserted, or deleted, to transform the
  28. predicted text into the reference text. The lower the distance, the more accurate the model is considered to be.
  29. Implementation is similar to `nltk.edit_distance <https://www.nltk.org/_modules/nltk/metrics/distance.html>`_.
  30. As input to ``forward`` and ``update`` the metric accepts the following input:
  31. - ``preds`` (:class:`~Sequence`): An iterable of hypothesis corpus
  32. - ``target`` (:class:`~Sequence`): An iterable of iterables of reference corpus
  33. As output of ``forward`` and ``compute`` the metric returns the following output:
  34. - ``eed`` (:class:`~torch.Tensor`): A tensor with the extended edit distance score. If `reduction` is set to
  35. ``'none'`` or ``None``, this has shape ``(N, )``, where ``N`` is the batch size. Otherwise, this is a scalar.
  36. Args:
  37. substitution_cost: The cost of substituting one character for another.
  38. reduction: a method to reduce metric score over samples.
  39. - ``'mean'``: takes the mean over samples
  40. - ``'sum'``: takes the sum over samples
  41. - ``None`` or ``'none'``: return the score per sample
  42. kwargs: Additional keyword arguments, see :ref:`Metric kwargs` for more info.
  43. Example::
  44. Basic example with two strings. Going from “rain” -> “sain” -> “shin” -> “shine” takes 3 edits:
  45. >>> from torchmetrics.text import EditDistance
  46. >>> metric = EditDistance()
  47. >>> metric(["rain"], ["shine"])
  48. tensor(3.)
  49. Example::
  50. Basic example with two strings and substitution cost of 2. Going from “rain” -> “sain” -> “shin” -> “shine”
  51. takes 3 edits, where two of them are substitutions:
  52. >>> from torchmetrics.text import EditDistance
  53. >>> metric = EditDistance(substitution_cost=2)
  54. >>> metric(["rain"], ["shine"])
  55. tensor(5.)
  56. Example::
  57. Multiple strings example:
  58. >>> from torchmetrics.text import EditDistance
  59. >>> metric = EditDistance(reduction=None)
  60. >>> metric(["rain", "lnaguaeg"], ["shine", "language"])
  61. tensor([3, 4], dtype=torch.int32)
  62. >>> metric = EditDistance(reduction="mean")
  63. >>> metric(["rain", "lnaguaeg"], ["shine", "language"])
  64. tensor(3.5000)
  65. """
  66. higher_is_better: bool = False
  67. is_differentiable: bool = False
  68. full_state_update: bool = False
  69. plot_lower_bound: float = 0.0
  70. edit_scores_list: List[Tensor]
  71. edit_scores: Tensor
  72. num_elements: Tensor
  73. def __init__(
  74. self, substitution_cost: int = 1, reduction: Optional[Literal["mean", "sum", "none"]] = "mean", **kwargs: Any
  75. ) -> None:
  76. super().__init__(**kwargs)
  77. if not (isinstance(substitution_cost, int) and substitution_cost >= 0):
  78. raise ValueError(
  79. f"Expected argument `substitution_cost` to be a positive integer, but got {substitution_cost}"
  80. )
  81. self.substitution_cost = substitution_cost
  82. allowed_reduction = (None, "mean", "sum", "none")
  83. if reduction not in allowed_reduction:
  84. raise ValueError(f"Expected argument `reduction` to be one of {allowed_reduction}, but got {reduction}")
  85. self.reduction = reduction
  86. if self.reduction == "none" or self.reduction is None:
  87. self.add_state("edit_scores_list", default=[], dist_reduce_fx="cat")
  88. else:
  89. self.add_state("edit_scores", default=torch.tensor(0), dist_reduce_fx="sum")
  90. self.add_state("num_elements", default=torch.tensor(0), dist_reduce_fx="sum")
  91. def update(self, preds: Union[str, Sequence[str]], target: Union[str, Sequence[str]]) -> None:
  92. """Update state with predictions and targets."""
  93. distance = _edit_distance_update(preds, target, self.substitution_cost)
  94. if self.reduction == "none" or self.reduction is None:
  95. self.edit_scores_list.append(distance)
  96. else:
  97. self.edit_scores += distance.sum()
  98. self.num_elements += distance.shape[0]
  99. def compute(self) -> torch.Tensor:
  100. """Compute the edit distance over state."""
  101. if self.reduction == "none" or self.reduction is None:
  102. return _edit_distance_compute(dim_zero_cat(self.edit_scores_list), 1, self.reduction)
  103. return _edit_distance_compute(self.edit_scores, self.num_elements, self.reduction)
  104. def plot(
  105. self, val: Optional[Union[Tensor, Sequence[Tensor]]] = None, ax: Optional[_AX_TYPE] = None
  106. ) -> _PLOT_OUT_TYPE:
  107. """Plot a single or multiple values from the metric.
  108. Args:
  109. val: Either a single result from calling `metric.forward` or `metric.compute` or a list of these results.
  110. If no value is provided, will automatically call `metric.compute` and plot that result.
  111. ax: An matplotlib axis object. If provided will add plot to that axis
  112. Returns:
  113. Figure and Axes object
  114. Raises:
  115. ModuleNotFoundError:
  116. If `matplotlib` is not installed
  117. .. plot::
  118. :scale: 75
  119. >>> # Example plotting a single value
  120. >>> from torchmetrics.text import EditDistance
  121. >>> metric = EditDistance()
  122. >>> preds = ["this is the prediction", "there is an other sample"]
  123. >>> target = ["this is the reference", "there is another one"]
  124. >>> metric.update(preds, target)
  125. >>> fig_, ax_ = metric.plot()
  126. .. plot::
  127. :scale: 75
  128. >>> # Example plotting multiple values
  129. >>> from torchmetrics.text import EditDistance
  130. >>> metric = EditDistance()
  131. >>> preds = ["this is the prediction", "there is an other sample"]
  132. >>> target = ["this is the reference", "there is another one"]
  133. >>> values = [ ]
  134. >>> for _ in range(10):
  135. ... values.append(metric(preds, target))
  136. >>> fig_, ax_ = metric.plot(values)
  137. """
  138. return self._plot(val, ax)