wer.py 5.1 KB

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