-
Notifications
You must be signed in to change notification settings - Fork 30
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request #213 from IINemo/fix_metrics
Added BLEU
- Loading branch information
Showing
4 changed files
with
53 additions
and
3 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,47 @@ | ||
import numpy as np | ||
from sacrebleu.metrics import BLEU | ||
|
||
from typing import List, Dict | ||
from .generation_metric import GenerationMetric | ||
|
||
|
||
class BLEUMetric(GenerationMetric): | ||
""" | ||
Calculates BLEU metric between model-generated texts and ground truth texts. | ||
""" | ||
|
||
def __init__(self): | ||
super().__init__(["greedy_texts"], "sequence") | ||
self.scorer = BLEU(effective_order=True, lowercase=True) | ||
|
||
def __str__(self): | ||
return "BLEU" | ||
|
||
def _score_single(self, t1: str, t2: str): | ||
return self.scorer.sentence_score( | ||
t1.strip().rstrip("."), [t2.strip().rstrip(".")] | ||
).score | ||
|
||
def __call__( | ||
self, | ||
stats: Dict[str, np.ndarray], | ||
target_texts: List[str], | ||
target_tokens: List[List[int]], | ||
) -> np.ndarray: | ||
""" | ||
Calculates BLEU score between stats['greedy_texts'] and target_texts. | ||
Parameters: | ||
stats (Dict[str, np.ndarray]): input statistics, which for multiple samples includes: | ||
* model-generated texts in 'greedy_texts' | ||
target_texts (List[str]): ground-truth texts | ||
target_tokens (List[List[int]]): corresponding token splits for each target text | ||
Returns: | ||
np.ndarray: list of BLEU Scores for each sample in input. | ||
""" | ||
return np.array( | ||
[ | ||
self._score_single(hyp, ref) | ||
for hyp, ref in zip(stats["greedy_texts"], target_texts) | ||
] | ||
) |