|
| 1 | +from typing import Callable, Sequence |
| 2 | + |
| 3 | +import torch |
| 4 | +from torch.types import Number |
| 5 | + |
| 6 | +from ignite.exceptions import NotComputableError |
| 7 | +from ignite.metrics.metric import Metric, reinit__is_reduced, sync_all_reduce |
| 8 | + |
| 9 | +__all__ = ["CharacterErrorRate"] |
| 10 | + |
| 11 | + |
| 12 | +def _edit_distance(ref: str, pred: str) -> int: |
| 13 | + """Computes the Levenshtein distance between two strings.""" |
| 14 | + n, m = len(ref), len(pred) |
| 15 | + if n == 0: |
| 16 | + return m |
| 17 | + if m == 0: |
| 18 | + return n |
| 19 | + dp = list(range(m + 1)) |
| 20 | + for i in range(1, n + 1): |
| 21 | + prev_diag = dp[0] |
| 22 | + dp[0] = i |
| 23 | + for j in range(1, m + 1): |
| 24 | + temp = dp[j] |
| 25 | + dp[j] = prev_diag if ref[i - 1] == pred[j - 1] else min(dp[j - 1], dp[j], prev_diag) + 1 |
| 26 | + prev_diag = temp |
| 27 | + return dp[m] |
| 28 | + |
| 29 | + |
| 30 | +class CharacterErrorRate(Metric): |
| 31 | + r"""Calculates the Character Error Rate (CER). |
| 32 | +
|
| 33 | + CER is defined as the total number of errors (substitutions, deletions, and insertions) |
| 34 | + at the character level divided by the total number of characters in the reference sequence. |
| 35 | +
|
| 36 | + .. math:: |
| 37 | + \text{CER} = \frac{S + D + I}{N} = \frac{S + D + I}{S + D + C} |
| 38 | +
|
| 39 | + where :math:`S` is the number of substitutions, :math:`D` is the number of deletions, |
| 40 | + :math:`I` is the number of insertions, :math:`C` is the number of correct characters, |
| 41 | + and :math:`N` is the total number of characters in the reference (:math:`N = S + D + C`). |
| 42 | +
|
| 43 | + - ``update`` must receive input of the form ``(y_pred, y)``. |
| 44 | + - `y_pred` and `y` both must be either ``str`` or list of ``str``. |
| 45 | + - When both inputs are plain ``str``, they are treated as a single-element batch. |
| 46 | +
|
| 47 | + Args: |
| 48 | + output_transform: a callable that is used to transform the |
| 49 | + :class:`~ignite.engine.engine.Engine`'s ``process_function``'s output into the |
| 50 | + form expected by the metric. |
| 51 | + device: specifies which device updates are accumulated on. By default, CPU. |
| 52 | + skip_unrolling: specifies whether output should be unrolled before being fed to update method. |
| 53 | +
|
| 54 | + Examples: |
| 55 | + For more information on how metric works with :class:`~ignite.engine.engine.Engine`, visit :ref:`attach-engine`. |
| 56 | +
|
| 57 | + .. testcode:: |
| 58 | +
|
| 59 | + from ignite.metrics.nlp import CharacterErrorRate |
| 60 | +
|
| 61 | + cer = CharacterErrorRate() |
| 62 | +
|
| 63 | + y_pred = ["the cat sat on the mat", "hello world"] |
| 64 | + y = ["the cat sat on mat", "hello world"] |
| 65 | +
|
| 66 | + cer.update((y_pred, y)) |
| 67 | + print(round(cer.compute(), 4)) |
| 68 | +
|
| 69 | + .. testoutput:: |
| 70 | +
|
| 71 | + 0.1379 |
| 72 | +
|
| 73 | + .. versionadded:: 0.5.2 |
| 74 | + """ |
| 75 | + |
| 76 | + def __init__( |
| 77 | + self, |
| 78 | + output_transform: Callable = lambda x: x, |
| 79 | + device: str | torch.device = torch.device("cpu"), |
| 80 | + skip_unrolling: bool = False, |
| 81 | + ): |
| 82 | + super().__init__(output_transform=output_transform, device=device, skip_unrolling=skip_unrolling) |
| 83 | + |
| 84 | + @reinit__is_reduced |
| 85 | + def reset(self) -> None: |
| 86 | + self._num_errors = torch.tensor(0.0, device=self._device) |
| 87 | + self._num_refs = torch.tensor(0.0, device=self._device) |
| 88 | + self._num_examples = torch.tensor(0.0, device=self._device) |
| 89 | + |
| 90 | + @reinit__is_reduced |
| 91 | + def update(self, output: Sequence[str]) -> None: |
| 92 | + y_pred, y = output[0], output[1] |
| 93 | + if not isinstance(y_pred, (str, list)) or not isinstance(y, (str, list)): |
| 94 | + raise TypeError(f"y_pred and y must be str or list[str], got y_pred: {type(y_pred)} and y: {type(y)}") |
| 95 | + if isinstance(y_pred, str) and isinstance(y, str): |
| 96 | + y_pred = [y_pred] |
| 97 | + y = [y] |
| 98 | + if not all(isinstance(p, str) for p in y_pred) or not all(isinstance(r, str) for r in y): |
| 99 | + raise TypeError("All elements of y_pred and y must be strings.") |
| 100 | + if len(y_pred) != len(y): |
| 101 | + raise ValueError( |
| 102 | + f"y_pred and y must have the same length. Got y_pred of length {len(y_pred)} and y of length {len(y)}." |
| 103 | + ) |
| 104 | + errors = 0.0 |
| 105 | + refs = 0.0 |
| 106 | + for p, r in zip(y_pred, y): |
| 107 | + errors += _edit_distance(r, p) |
| 108 | + refs += len(r) |
| 109 | + self._num_errors += errors |
| 110 | + self._num_refs += refs |
| 111 | + self._num_examples += 1 |
| 112 | + |
| 113 | + @sync_all_reduce("_num_errors", "_num_refs") |
| 114 | + def compute(self) -> Number: |
| 115 | + if self._num_examples == 0: |
| 116 | + raise NotComputableError("CharacterErrorRate must have at least one example before it can be computed.") |
| 117 | + if self._num_refs == 0: |
| 118 | + return 0.0 if self._num_errors == 0 else 1.0 |
| 119 | + return (self._num_errors / self._num_refs).item() |
0 commit comments