bleu.py 5.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158
  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. # referenced from
  15. # Library Name: torchtext
  16. # Authors: torchtext authors and @sluks
  17. # Date: 2020-07-18
  18. # Link: https://pytorch.org/text/_modules/torchtext/data/metrics.html#bleu_score
  19. from collections.abc import Sequence
  20. from typing import Any, Optional, Union
  21. import torch
  22. from torch import Tensor, tensor
  23. from torchmetrics import Metric
  24. from torchmetrics.functional.text.bleu import _bleu_score_compute, _bleu_score_update, _tokenize_fn
  25. from torchmetrics.utilities.imports import _MATPLOTLIB_AVAILABLE
  26. from torchmetrics.utilities.plot import _AX_TYPE, _PLOT_OUT_TYPE
  27. if not _MATPLOTLIB_AVAILABLE:
  28. __doctest_skip__ = ["BLEUScore.plot"]
  29. class BLEUScore(Metric):
  30. """Calculate `BLEU score`_ of machine translated text with one or more references.
  31. As input to ``forward`` and ``update`` the metric accepts the following input:
  32. - ``preds`` (:class:`~Sequence`): An iterable of machine translated corpus
  33. - ``target`` (:class:`~Sequence`): An iterable of iterables of reference corpus
  34. As output of ``forward`` and ``update`` the metric returns the following output:
  35. - ``bleu`` (:class:`~torch.Tensor`): A tensor with the BLEU Score
  36. Args:
  37. n_gram: Gram value ranged from 1 to 4
  38. smooth: Whether or not to apply smoothing, see `Machine Translation Evolution`_
  39. kwargs: Additional keyword arguments, see :ref:`Metric kwargs` for more info.
  40. weights:
  41. Weights used for unigrams, bigrams, etc. to calculate BLEU score.
  42. If not provided, uniform weights are used.
  43. Raises:
  44. ValueError: If a length of a list of weights is not ``None`` and not equal to ``n_gram``.
  45. Example:
  46. >>> from torchmetrics.text import BLEUScore
  47. >>> preds = ['the cat is on the mat']
  48. >>> target = [['there is a cat on the mat', 'a cat is on the mat']]
  49. >>> bleu = BLEUScore()
  50. >>> bleu(preds, target)
  51. tensor(0.7598)
  52. """
  53. is_differentiable: bool = False
  54. higher_is_better: bool = True
  55. full_state_update: bool = True
  56. plot_lower_bound: float = 0.0
  57. plot_upper_bound: float = 1.0
  58. preds_len: Tensor
  59. target_len: Tensor
  60. numerator: Tensor
  61. denominator: Tensor
  62. def __init__(
  63. self,
  64. n_gram: int = 4,
  65. smooth: bool = False,
  66. weights: Optional[Sequence[float]] = None,
  67. **kwargs: Any,
  68. ) -> None:
  69. super().__init__(**kwargs)
  70. self.n_gram = n_gram
  71. self.smooth = smooth
  72. if weights is not None and len(weights) != n_gram:
  73. raise ValueError(f"List of weights has different weights than `n_gram`: {len(weights)} != {n_gram}")
  74. self.weights = weights if weights is not None else [1.0 / n_gram] * n_gram
  75. self.add_state("preds_len", tensor(0.0), dist_reduce_fx="sum")
  76. self.add_state("target_len", tensor(0.0), dist_reduce_fx="sum")
  77. self.add_state("numerator", torch.zeros(self.n_gram), dist_reduce_fx="sum")
  78. self.add_state("denominator", torch.zeros(self.n_gram), dist_reduce_fx="sum")
  79. def update(self, preds: Sequence[str], target: Sequence[Sequence[str]]) -> None:
  80. """Update state with predictions and targets."""
  81. self.preds_len, self.target_len = _bleu_score_update(
  82. preds,
  83. target,
  84. self.numerator,
  85. self.denominator,
  86. self.preds_len,
  87. self.target_len,
  88. self.n_gram,
  89. _tokenize_fn,
  90. )
  91. def compute(self) -> Tensor:
  92. """Calculate BLEU score."""
  93. return _bleu_score_compute(
  94. self.preds_len, self.target_len, self.numerator, self.denominator, self.n_gram, self.weights, self.smooth
  95. )
  96. def plot(
  97. self, val: Optional[Union[Tensor, Sequence[Tensor]]] = None, ax: Optional[_AX_TYPE] = None
  98. ) -> _PLOT_OUT_TYPE:
  99. """Plot a single or multiple values from the metric.
  100. Args:
  101. val: Either a single result from calling `metric.forward` or `metric.compute` or a list of these results.
  102. If no value is provided, will automatically call `metric.compute` and plot that result.
  103. ax: An matplotlib axis object. If provided will add plot to that axis
  104. Returns:
  105. Figure and Axes object
  106. Raises:
  107. ModuleNotFoundError:
  108. If `matplotlib` is not installed
  109. .. plot::
  110. :scale: 75
  111. >>> # Example plotting a single value
  112. >>> from torchmetrics.text import BLEUScore
  113. >>> metric = BLEUScore()
  114. >>> preds = ['the cat is on the mat']
  115. >>> target = [['there is a cat on the mat', 'a cat is on the mat']]
  116. >>> metric.update(preds, target)
  117. >>> fig_, ax_ = metric.plot()
  118. .. plot::
  119. :scale: 75
  120. >>> # Example plotting multiple values
  121. >>> from torchmetrics.text import BLEUScore
  122. >>> metric = BLEUScore()
  123. >>> preds = ['the cat is on the mat']
  124. >>> target = [['there is a cat on the mat', 'a cat is on the mat']]
  125. >>> values = [ ]
  126. >>> for _ in range(10):
  127. ... values.append(metric(preds, target))
  128. >>> fig_, ax_ = metric.plot(values)
  129. """
  130. return self._plot(val, ax)