cer.py 5.2 KB

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