cer.py 2.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  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 typing import Union
  15. import torch
  16. from torch import Tensor, tensor
  17. from torchmetrics.functional.text.helper import _edit_distance
  18. def _cer_update(
  19. preds: Union[str, list[str]],
  20. target: Union[str, list[str]],
  21. ) -> tuple[Tensor, Tensor]:
  22. """Update the cer score with the current set of references and predictions.
  23. Args:
  24. preds: Transcription(s) to score as a string or list of strings
  25. target: Reference(s) for each speech input as a string or list of strings
  26. Returns:
  27. Number of edit operations to get from the reference to the prediction, summed over all samples
  28. Number of character overall references
  29. """
  30. if isinstance(preds, str):
  31. preds = [preds]
  32. if isinstance(target, str):
  33. target = [target]
  34. errors = tensor(0, dtype=torch.float)
  35. total = tensor(0, dtype=torch.float)
  36. for pred, tgt in zip(preds, target):
  37. pred_tokens = pred
  38. tgt_tokens = tgt
  39. errors += _edit_distance(list(pred_tokens), list(tgt_tokens))
  40. total += len(tgt_tokens)
  41. return errors, total
  42. def _cer_compute(errors: Tensor, total: Tensor) -> Tensor:
  43. """Compute the Character error rate.
  44. Args:
  45. errors: Number of edit operations to get from the reference to the prediction, summed over all samples
  46. total: Number of characters over all references
  47. Returns:
  48. Character error rate score
  49. """
  50. return errors / total
  51. def char_error_rate(preds: Union[str, list[str]], target: Union[str, list[str]]) -> Tensor:
  52. """Compute Character Error Rate used for performance of an automatic speech recognition system.
  53. This value indicates the percentage of characters that were incorrectly predicted. The lower the value, the better
  54. the performance of the ASR system with a CER of 0 being a perfect score.
  55. Args:
  56. preds: Transcription(s) to score as a string or list of strings
  57. target: Reference(s) for each speech input as a string or list of strings
  58. Returns:
  59. Character error rate score
  60. Examples:
  61. >>> preds = ["this is the prediction", "there is an other sample"]
  62. >>> target = ["this is the reference", "there is another one"]
  63. >>> char_error_rate(preds=preds, target=target)
  64. tensor(0.3415)
  65. """
  66. errors, total = _cer_update(preds, target)
  67. return _cer_compute(errors, total)