edit.py 4.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120
  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 Literal, Optional, Union
  16. import torch
  17. from torch import Tensor
  18. from torchmetrics.functional.text.helper import _LevenshteinEditDistance as _LE_distance
  19. def _edit_distance_update(
  20. preds: Union[str, Sequence[str]],
  21. target: Union[str, Sequence[str]],
  22. substitution_cost: int = 1,
  23. ) -> Tensor:
  24. if isinstance(preds, str):
  25. preds = [preds]
  26. if isinstance(target, str):
  27. target = [target]
  28. if not all(isinstance(x, str) for x in preds):
  29. raise ValueError(f"Expected all values in argument `preds` to be string type, but got {preds}")
  30. if not all(isinstance(x, str) for x in target):
  31. raise ValueError(f"Expected all values in argument `target` to be string type, but got {target}")
  32. if len(preds) != len(target):
  33. raise ValueError(
  34. f"Expected argument `preds` and `target` to have same length, but got {len(preds)} and {len(target)}"
  35. )
  36. distance = [
  37. _LE_distance(t, op_substitute=substitution_cost)(p)[0] # type: ignore[arg-type]
  38. for p, t in zip(preds, target)
  39. ]
  40. return torch.tensor(distance, dtype=torch.int)
  41. def _edit_distance_compute(
  42. edit_scores: Tensor,
  43. num_elements: Union[Tensor, int],
  44. reduction: Optional[Literal["mean", "sum", "none"]] = "mean",
  45. ) -> Tensor:
  46. """Compute final edit distance reduced over the batch."""
  47. if edit_scores.numel() == 0:
  48. return torch.tensor(0, dtype=torch.int32)
  49. if reduction == "mean":
  50. return edit_scores.sum() / num_elements
  51. if reduction == "sum":
  52. return edit_scores.sum()
  53. if reduction is None or reduction == "none":
  54. return edit_scores
  55. raise ValueError("Expected argument `reduction` to either be 'sum', 'mean', 'none' or None")
  56. def edit_distance(
  57. preds: Union[str, Sequence[str]],
  58. target: Union[str, Sequence[str]],
  59. substitution_cost: int = 1,
  60. reduction: Optional[Literal["mean", "sum", "none"]] = "mean",
  61. ) -> Tensor:
  62. """Calculates the Levenshtein edit distance between two sequences.
  63. The edit distance is the number of characters that need to be substituted, inserted, or deleted, to transform the
  64. predicted text into the reference text. The lower the distance, the more accurate the model is considered to be.
  65. Implementation is similar to `nltk.edit_distance <https://www.nltk.org/_modules/nltk/metrics/distance.html>`_.
  66. Args:
  67. preds: An iterable of predicted texts (strings).
  68. target: An iterable of reference texts (strings).
  69. substitution_cost: The cost of substituting one character for another.
  70. reduction: a method to reduce metric score over samples.
  71. - ``'mean'``: takes the mean over samples
  72. - ``'sum'``: takes the sum over samples
  73. - ``None`` or ``'none'``: return the score per sample
  74. Raises:
  75. ValueError:
  76. If ``preds`` and ``target`` do not have the same length.
  77. ValueError:
  78. If ``preds`` or ``target`` contain non-string values.
  79. Example::
  80. Basic example with two strings. Going from “rain” -> “sain” -> “shin” -> “shine” takes 3 edits:
  81. >>> from torchmetrics.functional.text import edit_distance
  82. >>> edit_distance(["rain"], ["shine"])
  83. tensor(3.)
  84. Example::
  85. Basic example with two strings and substitution cost of 2. Going from “rain” -> “sain” -> “shin” -> “shine”
  86. takes 3 edits, where two of them are substitutions:
  87. >>> from torchmetrics.functional.text import edit_distance
  88. >>> edit_distance(["rain"], ["shine"], substitution_cost=2)
  89. tensor(5.)
  90. Example::
  91. Multiple strings example:
  92. >>> from torchmetrics.functional.text import edit_distance
  93. >>> edit_distance(["rain", "lnaguaeg"], ["shine", "language"], reduction=None)
  94. tensor([3, 4], dtype=torch.int32)
  95. >>> edit_distance(["rain", "lnaguaeg"], ["shine", "language"], reduction="mean")
  96. tensor(3.5000)
  97. """
  98. distance = _edit_distance_update(preds, target, substitution_cost)
  99. return _edit_distance_compute(distance, num_elements=distance.numel(), reduction=reduction)