-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmetrics.py
140 lines (116 loc) · 4.86 KB
/
metrics.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
from collections import Counter
from nltk import ngrams
import re
import numpy as np
from nltk.translate import bleu_score as nltkbleu
import math
from torch.nn import functional as F
def sequence_loss(logits, targets, pad_idx=0):
""" functional interface of SequenceLoss"""
#assert logits.size()[:, :-1] == targets.size()
mask = targets != pad_idx
targets = targets.masked_select(mask)
targets = targets.view(-1)
logit = logits.masked_select(
mask.unsqueeze(2).expand_as(logits)
).contiguous().view(-1, logits.size(-1))
loss = F.cross_entropy(logit, targets, reduction='none')
assert (not math.isnan(loss.mean().item())
and not math.isinf(loss.mean().item()))
return loss
def bleu_corpus(hypothesis, references):
from nltk.translate.bleu_score import corpus_bleu
hypothesis = hypothesis.copy()
references = references.copy()
hypothesis = [hyp.split() for hyp in hypothesis]
references = [[ref.split()] for ref in references]
# hypothesis = [normalize_answer(hyp).split(" ") for hyp in hypothesis]
# references = [[normalize_answer(ref).split(" ")] for ref in references]
b1 = corpus_bleu(references, hypothesis, weights=(1.0/1.0,), smoothing_function=nltkbleu.SmoothingFunction(epsilon=1e-12).method1)
b2 = corpus_bleu(references, hypothesis, weights=(1.0/2.0, 1.0/2.0), smoothing_function=nltkbleu.SmoothingFunction(epsilon=1e-12).method1)
b3 = corpus_bleu(references, hypothesis, weights=(1.0/3.0, 1.0/3.0, 1.0/3.0), smoothing_function=nltkbleu.SmoothingFunction(epsilon=1e-12).method1)
b4 = corpus_bleu(references, hypothesis, weights=(1.0/4.0, 1.0/4.0, 1.0/4.0, 1.0/4.0), smoothing_function=nltkbleu.SmoothingFunction(epsilon=1e-12).method1)
return (b1, b2, b3, b4)
def bleu_metric(hypothesis, references):
return bleu_corpus(hypothesis, references)
def distinct_metric(hypothesis):
'''
compute distinct metric
:param hypothesis: list of str
:return:
'''
unigram_counter, bigram_counter = Counter(), Counter()
for hypo in hypothesis:
tokens = hypo.split()
unigram_counter.update(tokens)
bigram_counter.update(ngrams(tokens, 2))
distinct_1 = len(unigram_counter) / sum(unigram_counter.values())
distinct_2 = len(bigram_counter) / sum(bigram_counter.values())
return distinct_1, distinct_2
re_art = re.compile(r'\b(a|an|the)\b')
re_punc = re.compile(r'[!"#$%&()*+,-./:;<=>?@\[\]\\^`{|}~_\']')
def normalize_answer(s):
"""Lower text and remove punctuation, articles and extra whitespace."""
def remove_articles(text):
return re_art.sub(' ', text)
def white_space_fix(text):
return ' '.join(text.split())
def remove_punc(text):
return re_punc.sub(' ', text) # convert punctuation to spaces
def lower(text):
return text.lower()
return white_space_fix(remove_articles(remove_punc(lower(s))))
def _prec_recall_f1_score(pred_items, gold_items):
"""
Compute precision, recall and f1 given a set of gold and prediction items.
:param pred_items: iterable of predicted values
:param gold_items: iterable of gold values
:return: tuple (p, r, f1) for precision, recall, f1
"""
common = Counter(gold_items) & Counter(pred_items)
num_same = sum(common.values())
if num_same == 0:
return 0, 0, 0
precision = 1.0 * num_same / len(pred_items)
recall = 1.0 * num_same / len(gold_items)
f1 = (2 * precision * recall) / (precision + recall)
return precision, recall, f1
def _f1_score(guess, answers):
"""Return the max F1 score between the guess and *any* answer."""
if guess is None or answers is None:
return 0
g_tokens = normalize_answer(guess).split()
scores = [
_prec_recall_f1_score(g_tokens, normalize_answer(a).split()) for a in answers
]
return max(f1 for _, _, f1 in scores)
def _recall_score(guess, answers):
"""Return the max F1 score between the guess and *any* answer."""
if guess is None or answers is None:
return 0
g_tokens = normalize_answer(guess).split()
scores = [
_prec_recall_f1_score(g_tokens, normalize_answer(a).split()) for a in answers
]
return max(recall for _, recall, _ in scores)
def _precision_score(guess, answers):
"""Return the max F1 score between the guess and *any* answer."""
if guess is None or answers is None:
return 0
g_tokens = normalize_answer(guess).split()
scores = [
_prec_recall_f1_score(g_tokens, normalize_answer(a).split()) for a in answers
]
return max(precision for precision, _, _ in scores)
def f1_metric(hypothesis, references):
'''
calculate f1 metric
:param hypothesis: list of str
:param references: list of str
:return:
'''
f1 = []
for hyp, ref in zip(hypothesis, references):
_f1 = _f1_score(hyp, [ref])
f1.append(_f1)
return np.mean(f1)