mer.py 5.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141
  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, Optional, Union
  16. import torch
  17. from torch import Tensor, tensor
  18. from torchmetrics.functional.text.mer import _mer_compute, _mer_update
  19. from torchmetrics.metric import Metric
  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__ = ["MatchErrorRate.plot"]
  24. class MatchErrorRate(Metric):
  25. r"""Match Error Rate (`MER`_) is a common metric of the performance of an automatic speech recognition system.
  26. This value indicates the percentage of words that were incorrectly predicted and inserted.
  27. The lower the value, the better the performance of the ASR system with a MatchErrorRate of 0 being a perfect score.
  28. Match error rate can then be computed as:
  29. .. math::
  30. mer = \frac{S + D + I}{N + I} = \frac{S + D + I}{S + D + C + I}
  31. where:
  32. - :math:`S` is the number of substitutions,
  33. - :math:`D` is the number of deletions,
  34. - :math:`I` is the number of insertions,
  35. - :math:`C` is the number of correct words,
  36. - :math:`N` is the number of words in the reference (:math:`N=S+D+C`).
  37. As input to ``forward`` and ``update`` the metric accepts the following input:
  38. - ``preds`` (:class:`~List`): Transcription(s) to score as a string or list of strings
  39. - ``target`` (:class:`~List`): Reference(s) for each speech input as a string or list of strings
  40. As output of ``forward`` and ``compute`` the metric returns the following output:
  41. - ``mer`` (:class:`~torch.Tensor`): A tensor with the match error rate
  42. Args:
  43. kwargs: Additional keyword arguments, see :ref:`Metric kwargs` for more info.
  44. Examples:
  45. >>> from torchmetrics.text import MatchErrorRate
  46. >>> preds = ["this is the prediction", "there is an other sample"]
  47. >>> target = ["this is the reference", "there is another one"]
  48. >>> mer = MatchErrorRate()
  49. >>> mer(preds, target)
  50. tensor(0.4444)
  51. """
  52. is_differentiable: bool = False
  53. higher_is_better: bool = False
  54. full_state_update: bool = False
  55. plot_lower_bound: float = 0.0
  56. plot_upper_bound: float = 1.0
  57. errors: Tensor
  58. total: Tensor
  59. def __init__(
  60. self,
  61. **kwargs: Any,
  62. ) -> None:
  63. super().__init__(**kwargs)
  64. self.add_state("errors", tensor(0, dtype=torch.float), dist_reduce_fx="sum")
  65. self.add_state("total", tensor(0, dtype=torch.float), dist_reduce_fx="sum")
  66. def update(
  67. self,
  68. preds: Union[str, list[str]],
  69. target: Union[str, list[str]],
  70. ) -> None:
  71. """Update state with predictions and targets."""
  72. errors, total = _mer_update(preds, target)
  73. self.errors += errors
  74. self.total += total
  75. def compute(self) -> Tensor:
  76. """Calculate the Match error rate."""
  77. return _mer_compute(self.errors, self.total)
  78. def plot(
  79. self, val: Optional[Union[Tensor, Sequence[Tensor]]] = None, ax: Optional[_AX_TYPE] = None
  80. ) -> _PLOT_OUT_TYPE:
  81. """Plot a single or multiple values from the metric.
  82. Args:
  83. val: Either a single result from calling `metric.forward` or `metric.compute` or a list of these results.
  84. If no value is provided, will automatically call `metric.compute` and plot that result.
  85. ax: An matplotlib axis object. If provided will add plot to that axis
  86. Returns:
  87. Figure and Axes object
  88. Raises:
  89. ModuleNotFoundError:
  90. If `matplotlib` is not installed
  91. .. plot::
  92. :scale: 75
  93. >>> # Example plotting a single value
  94. >>> from torchmetrics.text import MatchErrorRate
  95. >>> metric = MatchErrorRate()
  96. >>> preds = ["this is the prediction", "there is an other sample"]
  97. >>> target = ["this is the reference", "there is another one"]
  98. >>> metric.update(preds, target)
  99. >>> fig_, ax_ = metric.plot()
  100. .. plot::
  101. :scale: 75
  102. >>> # Example plotting multiple values
  103. >>> from torchmetrics.text import MatchErrorRate
  104. >>> metric = MatchErrorRate()
  105. >>> preds = ["this is the prediction", "there is an other sample"]
  106. >>> target = ["this is the reference", "there is another one"]
  107. >>> values = [ ]
  108. >>> for _ in range(10):
  109. ... values.append(metric(preds, target))
  110. >>> fig_, ax_ = metric.plot(values)
  111. """
  112. return self._plot(val, ax)