rouge.py 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513
  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. import re
  15. from collections import Counter
  16. from collections.abc import Sequence
  17. from typing import Any, Callable, List, Optional, Union
  18. import torch
  19. from torch import Tensor, tensor
  20. from typing_extensions import Literal
  21. from torchmetrics.utilities.imports import _NLTK_AVAILABLE
  22. __doctest_requires__ = {("rouge_score", "_rouge_score_update"): ["nltk"]}
  23. ALLOWED_ROUGE_KEYS: dict[str, Union[int, str]] = {
  24. "rouge1": 1,
  25. "rouge2": 2,
  26. "rouge3": 3,
  27. "rouge4": 4,
  28. "rouge5": 5,
  29. "rouge6": 6,
  30. "rouge7": 7,
  31. "rouge8": 8,
  32. "rouge9": 9,
  33. "rougeL": "L",
  34. "rougeLsum": "Lsum",
  35. }
  36. ALLOWED_ACCUMULATE_VALUES = ("avg", "best")
  37. def _ensure_nltk_punkt_is_downloaded() -> None:
  38. """Check whether `nltk` `punkt` is downloaded.
  39. If not, try to download if a machine is connected to the internet.
  40. """
  41. import nltk
  42. try:
  43. nltk.data.find("tokenizers/punkt_tab")
  44. except LookupError:
  45. try:
  46. nltk.download("punkt_tab", quiet=True, force=False, halt_on_error=False, raise_on_error=True)
  47. except ValueError as err:
  48. raise OSError(
  49. "`nltk` resource `punkt` is not available on a disk and cannot be downloaded as a machine is not "
  50. "connected to the internet."
  51. ) from err
  52. def _split_sentence(x: str) -> Sequence[str]:
  53. """Split sentence to get rougeLsum scores matching published rougeL scores for BART and PEGASUS."""
  54. if not _NLTK_AVAILABLE:
  55. raise ModuleNotFoundError("ROUGE-Lsum calculation requires that `nltk` is installed. Use `pip install nltk`.")
  56. import nltk
  57. _ensure_nltk_punkt_is_downloaded()
  58. re.sub("<n>", "", x) # remove pegasus newline char
  59. return nltk.sent_tokenize(x)
  60. def _compute_metrics(hits_or_lcs: int, pred_len: int, target_len: int) -> dict[str, Tensor]:
  61. """Compute overall metrics.
  62. This function computes precision, recall and F1 score based on hits/lcs, the length of lists of tokenizer
  63. predicted and target sentences.
  64. Args:
  65. hits_or_lcs: A number of matches or a length of the longest common subsequence.
  66. pred_len: A length of a tokenized predicted sentence.
  67. target_len: A length of a tokenized target sentence.
  68. """
  69. precision = hits_or_lcs / pred_len
  70. recall = hits_or_lcs / target_len
  71. if precision == recall == 0.0:
  72. return {"precision": tensor(0.0), "recall": tensor(0.0), "fmeasure": tensor(0.0)}
  73. fmeasure = 2 * precision * recall / (precision + recall)
  74. return {"precision": tensor(precision), "recall": tensor(recall), "fmeasure": tensor(fmeasure)}
  75. def _lcs(
  76. pred_tokens: Sequence[str], target_tokens: Sequence[str], return_full_table: bool = False
  77. ) -> Union[int, Sequence[Sequence[int]]]:
  78. """DP algorithm to compute the length of the longest common subsequence.
  79. Args:
  80. pred_tokens: A tokenized predicted sentence.
  81. target_tokens: A tokenized target sentence.
  82. return_full_table: If the full table of logest common subsequence should be returned or just the largest
  83. """
  84. lcs = [[0] * (len(pred_tokens) + 1) for _ in range(len(target_tokens) + 1)]
  85. for i in range(1, len(target_tokens) + 1):
  86. for j in range(1, len(pred_tokens) + 1):
  87. if target_tokens[i - 1] == pred_tokens[j - 1]:
  88. lcs[i][j] = lcs[i - 1][j - 1] + 1
  89. else:
  90. lcs[i][j] = max(lcs[i - 1][j], lcs[i][j - 1])
  91. if return_full_table:
  92. return lcs
  93. return lcs[-1][-1]
  94. def _backtracked_lcs(
  95. lcs_table: Sequence[Sequence[int]], pred_tokens: Sequence[str], target_tokens: Sequence[str]
  96. ) -> Sequence[int]:
  97. """Backtrack LCS table.
  98. Args:
  99. lcs_table: A table containing information for the calculation of the longest common subsequence.
  100. pred_tokens: A tokenized predicted sentence.
  101. target_tokens: A tokenized target sentence.
  102. """
  103. i = len(pred_tokens)
  104. j = len(target_tokens)
  105. backtracked_lcs: list[int] = []
  106. while i > 0 and j > 0:
  107. if pred_tokens[i - 1] == target_tokens[j - 1]:
  108. backtracked_lcs.insert(0, j - 1)
  109. i -= 1
  110. j -= 1
  111. elif lcs_table[j][i - 1] > lcs_table[j - 1][i]:
  112. i -= 1
  113. else:
  114. j -= 1
  115. return backtracked_lcs
  116. def _union_lcs(pred_tokens_list: Sequence[Sequence[str]], target_tokens: Sequence[str]) -> Sequence[str]:
  117. r"""Find union LCS between a target sentence and iterable of predicted tokens.
  118. Args:
  119. pred_tokens_list: A tokenized predicted sentence split by ``'\n'``.
  120. target_tokens: A tokenized single part of target sentence split by ``'\n'``.
  121. """
  122. def lcs_ind(pred_tokens: Sequence[str], target_tokens: Sequence[str]) -> Sequence[int]:
  123. """Return one of the longest of longest common subsequence via backtracked lcs table."""
  124. lcs_table: Sequence[Sequence[int]] = _lcs(pred_tokens, target_tokens, return_full_table=True) # type: ignore
  125. return _backtracked_lcs(lcs_table, pred_tokens, target_tokens)
  126. def find_union(lcs_tables: Sequence[Sequence[int]]) -> Sequence[int]:
  127. """Find union LCS given a list of LCS."""
  128. return sorted(set().union(*lcs_tables))
  129. lcs_tables = [lcs_ind(pred_tokens, target_tokens) for pred_tokens in pred_tokens_list]
  130. return [target_tokens[i] for i in find_union(lcs_tables)]
  131. def _normalize_and_tokenize_text(
  132. text: str,
  133. stemmer: Optional[Any] = None,
  134. normalizer: Optional[Callable[[str], str]] = None,
  135. tokenizer: Optional[Callable[[str], Sequence[str]]] = None,
  136. ) -> Sequence[str]:
  137. """Rouge score should be calculated only over lowercased words and digits.
  138. Optionally, Porter stemmer can be used to strip word suffixes to improve matching. The text normalization follows
  139. the implemantion from `Rouge score_Text Normalizition`_.
  140. Args:
  141. text: An input sentence.
  142. stemmer: Porter stemmer instance to strip word suffixes to improve matching.
  143. normalizer: A user's own normalizer function.
  144. If this is ``None``, replacing any non-alpha-numeric characters with spaces is default.
  145. This function must take a ``str`` and return a ``str``.
  146. tokenizer:
  147. A user's own tokenizer function. If this is ``None``, splitting by spaces is default
  148. This function must take a ``str`` and return ``Sequence[str]``
  149. """
  150. # If normalizer is none, replace any non-alpha-numeric characters with spaces.
  151. text = normalizer(text) if callable(normalizer) else re.sub(r"[^a-z0-9]+", " ", text.lower())
  152. # If tokenizer is none, splitting by spaces
  153. tokens = tokenizer(text) if callable(tokenizer) else re.split(r"\s+", text)
  154. if stemmer:
  155. # Only stem words more than 3 characters long.
  156. tokens = [stemmer.stem(x) if len(x) > 3 else x for x in tokens]
  157. # One final check to drop any empty or invalid tokens.
  158. return [x for x in tokens if (isinstance(x, str) and len(x) > 0)]
  159. def _rouge_n_score(pred: Sequence[str], target: Sequence[str], n_gram: int) -> dict[str, Tensor]:
  160. """Compute precision, recall and F1 score for the Rouge-N metric.
  161. Args:
  162. pred: A predicted sentence.
  163. target: A target sentence.
  164. n_gram: N-gram overlap.
  165. """
  166. def _create_ngrams(tokens: Sequence[str], n: int) -> Counter:
  167. ngrams: Counter = Counter()
  168. for ngram in (tuple(tokens[i : i + n]) for i in range(len(tokens) - n + 1)):
  169. ngrams[ngram] += 1
  170. return ngrams
  171. pred_ngrams, target_ngrams = _create_ngrams(pred, n_gram), _create_ngrams(target, n_gram)
  172. pred_len, target_len = sum(pred_ngrams.values()), sum(target_ngrams.values())
  173. if 0 in (pred_len, target_len):
  174. return {"precision": tensor(0.0), "recall": tensor(0.0), "fmeasure": tensor(0.0)}
  175. # It is sufficient to take a set(pred_tokenized) for hits count as we consider intersenction of pred & target
  176. hits = sum(min(pred_ngrams[w], target_ngrams[w]) for w in set(pred_ngrams))
  177. return _compute_metrics(hits, max(pred_len, 1), max(target_len, 1))
  178. def _rouge_l_score(pred: Sequence[str], target: Sequence[str]) -> dict[str, Tensor]:
  179. """Compute precision, recall and F1 score for the Rouge-L metric.
  180. Args:
  181. pred: A predicted sentence.
  182. target: A target sentence.
  183. """
  184. pred_len, target_len = len(pred), len(target)
  185. if 0 in (pred_len, target_len):
  186. return {"precision": tensor(0.0), "recall": tensor(0.0), "fmeasure": tensor(0.0)}
  187. lcs: int = _lcs(pred, target) # type: ignore
  188. return _compute_metrics(lcs, pred_len, target_len)
  189. def _rouge_lsum_score(pred: Sequence[Sequence[str]], target: Sequence[Sequence[str]]) -> dict[str, Tensor]:
  190. r"""Compute precision, recall and F1 score for the Rouge-LSum metric.
  191. More information can be found in Section 3.2 of the referenced paper [1]. This implementation follow the official
  192. implementation from:
  193. https://github.com/google-research/google-research/blob/master/rouge/rouge_scorer.py.
  194. Args:
  195. pred: An iterable of predicted sentence split by '\n'.
  196. target: An iterable target sentence split by '\n'.
  197. References:
  198. [1] ROUGE: A Package for Automatic Evaluation of Summaries by Chin-Yew Lin. https://aclanthology.org/W04-1013/
  199. """
  200. pred_len = sum(map(len, pred))
  201. target_len = sum(map(len, target))
  202. if 0 in (pred_len, target_len):
  203. return {"precision": tensor(0.0), "recall": tensor(0.0), "fmeasure": tensor(0.0)}
  204. # Get token counts
  205. def _get_token_counts(sentences: Sequence[Sequence[str]]) -> Counter:
  206. ngrams: Counter = Counter()
  207. for sentence in sentences:
  208. ngrams.update(sentence)
  209. return ngrams
  210. pred_tokens_count = _get_token_counts(pred)
  211. target_tokens_count = _get_token_counts(target)
  212. # Calculate hits
  213. hits = 0
  214. for tgt in target:
  215. lcs = _union_lcs(pred, tgt)
  216. for token in lcs:
  217. if pred_tokens_count[token] > 0 and target_tokens_count[token] > 0:
  218. hits += 1
  219. pred_tokens_count[token] -= 1
  220. target_tokens_count[token] -= 1
  221. return _compute_metrics(hits, pred_len, target_len)
  222. def _rouge_score_update(
  223. preds: Sequence[str],
  224. target: Sequence[Sequence[str]],
  225. rouge_keys_values: list[Union[int, str]],
  226. accumulate: str,
  227. stemmer: Optional[Any] = None,
  228. normalizer: Optional[Callable[[str], str]] = None,
  229. tokenizer: Optional[Callable[[str], Sequence[str]]] = None,
  230. ) -> dict[Union[int, str], list[dict[str, Tensor]]]:
  231. """Update the rouge score with the current set of predicted and target sentences.
  232. Args:
  233. preds: An iterable of predicted sentences.
  234. target: An iterable of iterable of target sentences.
  235. rouge_keys_values: List of N-grams/'L'/'Lsum' arguments.
  236. accumulate: Useful in case of multi-reference rouge score.
  237. ``avg`` takes the avg of all references with respect to predictions
  238. ``best`` takes the best fmeasure score obtained between prediction and multiple corresponding references.
  239. Allowed values are ``avg`` and ``best``.
  240. stemmer: Porter stemmer instance to strip word suffixes to improve matching.
  241. normalizer:
  242. A user's own normalizer function.
  243. If this is ``None``, replacing any non-alpha-numeric characters with spaces is default.
  244. This function must take a `str` and return a `str`.
  245. tokenizer:
  246. A user's own tokenizer function. If this is ``None``, splitting by spaces is default
  247. This function must take a `str` and return `Sequence[str]`
  248. Example:
  249. >>> preds = ["My name is John"]
  250. >>> target = [["Is your name John"]]
  251. >>> from pprint import pprint
  252. >>> score = _rouge_score_update(preds, target, rouge_keys_values=[1, 2, 'L'], accumulate='best')
  253. >>> pprint(score)
  254. {1: [{'fmeasure': tensor(0.7500),
  255. 'precision': tensor(0.7500),
  256. 'recall': tensor(0.7500)}],
  257. 2: [{'fmeasure': tensor(0.), 'precision': tensor(0.), 'recall': tensor(0.)}],
  258. 'L': [{'fmeasure': tensor(0.5000),
  259. 'precision': tensor(0.5000),
  260. 'recall': tensor(0.5000)}]}
  261. """
  262. results: dict[Union[int, str], list[dict[str, Tensor]]] = {rouge_key: [] for rouge_key in rouge_keys_values}
  263. for pred_raw, target_raw in zip(preds, target):
  264. result_inner: dict[Union[int, str], dict[str, Tensor]] = {rouge_key: {} for rouge_key in rouge_keys_values}
  265. result_avg: dict[Union[int, str], list[dict[str, Tensor]]] = {rouge_key: [] for rouge_key in rouge_keys_values}
  266. list_results = []
  267. pred = _normalize_and_tokenize_text(pred_raw, stemmer, normalizer, tokenizer)
  268. if "Lsum" in rouge_keys_values:
  269. pred_lsum = [
  270. _normalize_and_tokenize_text(pred_sentence, stemmer, normalizer, tokenizer)
  271. for pred_sentence in _split_sentence(pred_raw)
  272. ]
  273. for target_raw_inner in target_raw:
  274. tgt = _normalize_and_tokenize_text(target_raw_inner, stemmer, normalizer, tokenizer)
  275. if "Lsum" in rouge_keys_values:
  276. target_lsum = [
  277. _normalize_and_tokenize_text(tgt_sentence, stemmer, normalizer, tokenizer)
  278. for tgt_sentence in _split_sentence(target_raw_inner)
  279. ]
  280. for rouge_key in rouge_keys_values:
  281. if isinstance(rouge_key, int):
  282. score = _rouge_n_score(pred, tgt, rouge_key)
  283. elif rouge_key == "L":
  284. score = _rouge_l_score(pred, tgt)
  285. elif rouge_key == "Lsum":
  286. score = _rouge_lsum_score(pred_lsum, target_lsum)
  287. result_inner[rouge_key] = score
  288. result_avg[rouge_key].append(score)
  289. list_results.append(result_inner.copy())
  290. if accumulate == "best":
  291. for k in rouge_keys_values:
  292. index = torch.argmax(torch.tensor([s[k]["fmeasure"] for s in list_results]))
  293. results[k].append(list_results[index][k])
  294. elif accumulate == "avg":
  295. new_result_avg: dict[Union[int, str], dict[str, Tensor]] = {
  296. rouge_key: {} for rouge_key in rouge_keys_values
  297. }
  298. for rouge_key, metrics in result_avg.items():
  299. _dict_metric_score_batch: dict[str, List[Tensor]] = {}
  300. for metric in metrics:
  301. for _type, value in metric.items():
  302. if _type not in _dict_metric_score_batch:
  303. _dict_metric_score_batch[_type] = []
  304. _dict_metric_score_batch[_type].append(value)
  305. new_result_avg[rouge_key] = {
  306. _type: torch.tensor(_dict_metric_score_batch[_type]).mean() for _type in _dict_metric_score_batch
  307. }
  308. for rouge_key in rouge_keys_values:
  309. results[rouge_key].append(new_result_avg[rouge_key]) # todo
  310. return results
  311. def _rouge_score_compute(sentence_results: dict[str, List[Tensor]]) -> dict[str, Tensor]:
  312. """Compute the combined ROUGE metric for all the input set of predicted and target sentences.
  313. Args:
  314. sentence_results: Rouge-N/Rouge-L/Rouge-LSum metrics calculated for single sentence.
  315. """
  316. results: dict[str, Tensor] = {}
  317. # Obtain mean scores for individual rouge metrics
  318. if sentence_results == {}:
  319. return results
  320. for rouge_key, scores in sentence_results.items():
  321. results[rouge_key] = torch.tensor(scores).mean()
  322. return results
  323. def rouge_score(
  324. preds: Union[str, Sequence[str]],
  325. target: Union[str, Sequence[str], Sequence[Sequence[str]]],
  326. accumulate: Literal["avg", "best"] = "best",
  327. use_stemmer: bool = False,
  328. normalizer: Optional[Callable[[str], str]] = None,
  329. tokenizer: Optional[Callable[[str], Sequence[str]]] = None,
  330. rouge_keys: Union[str, tuple[str, ...]] = ("rouge1", "rouge2", "rougeL", "rougeLsum"),
  331. ) -> dict[str, Tensor]:
  332. """Calculate `Calculate Rouge Score`_ , used for automatic summarization.
  333. Args:
  334. preds: An iterable of predicted sentences or a single predicted sentence.
  335. target:
  336. An iterable of iterables of target sentences or an iterable of target sentences or a single target sentence.
  337. accumulate:
  338. Useful in case of multi-reference rouge score.
  339. - ``avg`` takes the avg of all references with respect to predictions
  340. - ``best`` takes the best fmeasure score obtained between prediction and multiple corresponding references.
  341. use_stemmer: Use Porter stemmer to strip word suffixes to improve matching.
  342. normalizer: A user's own normalizer function.
  343. If this is ``None``, replacing any non-alpha-numeric characters with spaces is default.
  344. This function must take a ``str`` and return a ``str``.
  345. tokenizer: A user's own tokenizer function. If this is ``None``, splitting by spaces is default
  346. This function must take a ``str`` and return ``Sequence[str]``
  347. rouge_keys: A list of rouge types to calculate.
  348. Keys that are allowed are ``rougeL``, ``rougeLsum``, and ``rouge1`` through ``rouge9``.
  349. Return:
  350. Python dictionary of rouge scores for each input rouge key.
  351. Example:
  352. >>> from torchmetrics.functional.text.rouge import rouge_score
  353. >>> preds = "My name is John"
  354. >>> target = "Is your name John"
  355. >>> from pprint import pprint
  356. >>> pprint(rouge_score(preds, target))
  357. {'rouge1_fmeasure': tensor(0.7500),
  358. 'rouge1_precision': tensor(0.7500),
  359. 'rouge1_recall': tensor(0.7500),
  360. 'rouge2_fmeasure': tensor(0.),
  361. 'rouge2_precision': tensor(0.),
  362. 'rouge2_recall': tensor(0.),
  363. 'rougeL_fmeasure': tensor(0.5000),
  364. 'rougeL_precision': tensor(0.5000),
  365. 'rougeL_recall': tensor(0.5000),
  366. 'rougeLsum_fmeasure': tensor(0.5000),
  367. 'rougeLsum_precision': tensor(0.5000),
  368. 'rougeLsum_recall': tensor(0.5000)}
  369. Raises:
  370. ModuleNotFoundError:
  371. If the python package ``nltk`` is not installed.
  372. ValueError:
  373. If any of the ``rouge_keys`` does not belong to the allowed set of keys.
  374. References:
  375. [1] ROUGE: A Package for Automatic Evaluation of Summaries by Chin-Yew Lin. https://aclanthology.org/W04-1013/
  376. """
  377. if use_stemmer:
  378. if not _NLTK_AVAILABLE:
  379. raise ModuleNotFoundError("Stemmer requires that `nltk` is installed. Use `pip install nltk`.")
  380. import nltk
  381. stemmer = nltk.stem.porter.PorterStemmer() if use_stemmer else None
  382. if not isinstance(rouge_keys, tuple):
  383. rouge_keys = (rouge_keys,)
  384. for key in rouge_keys:
  385. if key not in ALLOWED_ROUGE_KEYS:
  386. raise ValueError(f"Got unknown rouge key {key}. Expected to be one of {list(ALLOWED_ROUGE_KEYS.keys())}")
  387. rouge_keys_values = [ALLOWED_ROUGE_KEYS[key] for key in rouge_keys]
  388. if isinstance(target, list) and all(isinstance(tgt, str) for tgt in target):
  389. target = [target] if isinstance(preds, str) else [[tgt] for tgt in target]
  390. if isinstance(preds, str):
  391. preds = [preds]
  392. if isinstance(target, str):
  393. target = [[target]]
  394. sentence_results: dict[Union[int, str], list[dict[str, Tensor]]] = _rouge_score_update(
  395. preds,
  396. target,
  397. rouge_keys_values,
  398. stemmer=stemmer,
  399. normalizer=normalizer,
  400. tokenizer=tokenizer,
  401. accumulate=accumulate,
  402. )
  403. output: dict[str, List[Tensor]] = {
  404. f"rouge{rouge_key}_{tp}": [] for rouge_key in rouge_keys_values for tp in ["fmeasure", "precision", "recall"]
  405. }
  406. for rouge_key, metrics in sentence_results.items():
  407. for metric in metrics:
  408. for tp, value in metric.items():
  409. output[f"rouge{rouge_key}_{tp}"].append(value) # todo
  410. return _rouge_score_compute(output)