-
Notifications
You must be signed in to change notification settings - Fork 1
/
rouge_metric.py
716 lines (548 loc) · 25.2 KB
/
rouge_metric.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
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
import os
import re
import platform
import itertools
import collections
import pkg_resources # pip install py-rouge
from io import open
from konlpy.tag import Mecab
class Rouge:
DEFAULT_METRICS = {"rouge-n"}
DEFAULT_N = 1
STATS = ["f", "p", "r"]
AVAILABLE_METRICS = {"rouge-n", "rouge-l", "rouge-w"}
AVAILABLE_LENGTH_LIMIT_TYPES = {"words", "bytes"}
REMOVE_CHAR_PATTERN = re.compile("[^A-Za-z0-9가-힣]")
def __init__(
self,
metrics=None,
max_n=None,
limit_length=True,
length_limit=1000,
length_limit_type="words",
apply_avg=True,
apply_best=False,
use_tokenizer=True,
alpha=0.5,
weight_factor=1.0,
):
self.metrics = metrics[:] if metrics is not None else Rouge.DEFAULT_METRICS
for m in self.metrics:
if m not in Rouge.AVAILABLE_METRICS:
raise ValueError("Unknown metric '{}'".format(m))
self.max_n = max_n if "rouge-n" in self.metrics else None
# Add all rouge-n metrics
if self.max_n is not None:
index_rouge_n = self.metrics.index("rouge-n")
del self.metrics[index_rouge_n]
self.metrics += ["rouge-{}".format(n) for n in range(1, self.max_n + 1)]
self.metrics = set(self.metrics)
self.limit_length = limit_length
if self.limit_length:
if length_limit_type not in Rouge.AVAILABLE_LENGTH_LIMIT_TYPES:
raise ValueError("Unknown length_limit_type '{}'".format(length_limit_type))
self.length_limit = length_limit
if self.length_limit == 0:
self.limit_length = False
self.length_limit_type = length_limit_type
self.use_tokenizer = use_tokenizer
if use_tokenizer:
self.tokenizer = Mecab()
self.apply_avg = apply_avg
self.apply_best = apply_best
self.alpha = alpha
self.weight_factor = weight_factor
if self.weight_factor <= 0:
raise ValueError("ROUGE-W weight factor must greater than 0.")
def tokenize_text(self, text):
if self.use_tokenizer:
return self.tokenizer.morphs(text)
else:
return text
@staticmethod
def split_into_sentences(text):
return text.split("\n")
@staticmethod
def _get_ngrams(n, text):
ngram_set = collections.defaultdict(int)
max_index_ngram_start = len(text) - n
for i in range(max_index_ngram_start + 1):
ngram_set[tuple(text[i : i + n])] += 1
return ngram_set
@staticmethod
def _split_into_words(sentences):
return list(itertools.chain(*[_.split() for _ in sentences]))
@staticmethod
def _get_word_ngrams_and_length(n, sentences):
assert len(sentences) > 0
assert n > 0
tokens = Rouge._split_into_words(sentences)
return Rouge._get_ngrams(n, tokens), tokens, len(tokens) - (n - 1)
@staticmethod
def _get_unigrams(sentences):
assert len(sentences) > 0
tokens = Rouge._split_into_words(sentences)
unigram_set = collections.defaultdict(int)
for token in tokens:
unigram_set[token] += 1
return unigram_set, len(tokens)
@staticmethod
def _compute_p_r_f_score(
evaluated_count,
reference_count,
overlapping_count,
alpha=0.5,
weight_factor=1.0,
):
precision = 0.0 if evaluated_count == 0 else overlapping_count / float(evaluated_count)
if weight_factor != 1.0:
precision = precision ** (1.0 / weight_factor)
recall = 0.0 if reference_count == 0 else overlapping_count / float(reference_count)
if weight_factor != 1.0:
recall = recall ** (1.0 / weight_factor)
f1_score = Rouge._compute_f_score(precision, recall, alpha)
return {"f": f1_score, "p": precision, "r": recall}
@staticmethod
def _compute_f_score(precision, recall, alpha=0.5):
return (
0.0
if (recall == 0.0 or precision == 0.0)
else precision * recall / ((1 - alpha) * precision + alpha * recall)
)
@staticmethod
def _compute_ngrams(evaluated_sentences, reference_sentences, n):
if len(evaluated_sentences) <= 0 or len(reference_sentences) <= 0:
raise ValueError("Collections must contain at least 1 sentence.")
evaluated_ngrams, _, evaluated_count = Rouge._get_word_ngrams_and_length(
n, evaluated_sentences
)
reference_ngrams, _, reference_count = Rouge._get_word_ngrams_and_length(
n, reference_sentences
)
# Gets the overlapping ngrams between evaluated and reference
overlapping_ngrams = set(evaluated_ngrams.keys()).intersection(set(reference_ngrams.keys()))
overlapping_count = 0
for ngram in overlapping_ngrams:
overlapping_count += min(evaluated_ngrams[ngram], reference_ngrams[ngram])
return evaluated_count, reference_count, overlapping_count
@staticmethod
def _compute_ngrams_lcs(evaluated_sentences, reference_sentences, weight_factor=1.0):
def _lcs(x, y):
m = len(x)
n = len(y)
vals = collections.defaultdict(int)
dirs = collections.defaultdict(int)
for i in range(1, m + 1):
for j in range(1, n + 1):
if x[i - 1] == y[j - 1]:
vals[i, j] = vals[i - 1, j - 1] + 1
dirs[i, j] = "|"
elif vals[i - 1, j] >= vals[i, j - 1]:
vals[i, j] = vals[i - 1, j]
dirs[i, j] = "^"
else:
vals[i, j] = vals[i, j - 1]
dirs[i, j] = "<"
return vals, dirs
def _wlcs(x, y, weight_factor):
m = len(x)
n = len(y)
vals = collections.defaultdict(float)
dirs = collections.defaultdict(int)
lengths = collections.defaultdict(int)
for i in range(1, m + 1):
for j in range(1, n + 1):
if x[i - 1] == y[j - 1]:
length_tmp = lengths[i - 1, j - 1]
vals[i, j] = (
vals[i - 1, j - 1]
+ (length_tmp + 1) ** weight_factor
- length_tmp ** weight_factor
)
dirs[i, j] = "|"
lengths[i, j] = length_tmp + 1
elif vals[i - 1, j] >= vals[i, j - 1]:
vals[i, j] = vals[i - 1, j]
dirs[i, j] = "^"
lengths[i, j] = 0
else:
vals[i, j] = vals[i, j - 1]
dirs[i, j] = "<"
lengths[i, j] = 0
return vals, dirs
def _mark_lcs(mask, dirs, m, n):
while m != 0 and n != 0:
if dirs[m, n] == "|":
m -= 1
n -= 1
mask[m] = 1
elif dirs[m, n] == "^":
m -= 1
elif dirs[m, n] == "<":
n -= 1
else:
raise UnboundLocalError("Illegal move")
return mask
if len(evaluated_sentences) <= 0 or len(reference_sentences) <= 0:
raise ValueError("Collections must contain at least 1 sentence.")
evaluated_unigrams_dict, evaluated_count = Rouge._get_unigrams(evaluated_sentences)
reference_unigrams_dict, reference_count = Rouge._get_unigrams(reference_sentences)
# Has to use weight factor for WLCS
use_WLCS = weight_factor != 1.0
if use_WLCS:
evaluated_count = evaluated_count ** weight_factor
reference_count = 0
overlapping_count = 0.0
for reference_sentence in reference_sentences:
reference_sentence_tokens = reference_sentence.split()
if use_WLCS:
reference_count += len(reference_sentence_tokens) ** weight_factor
hit_mask = [0 for _ in range(len(reference_sentence_tokens))]
for evaluated_sentence in evaluated_sentences:
evaluated_sentence_tokens = evaluated_sentence.split()
if use_WLCS:
_, lcs_dirs = _wlcs(
reference_sentence_tokens,
evaluated_sentence_tokens,
weight_factor,
)
else:
_, lcs_dirs = _lcs(reference_sentence_tokens, evaluated_sentence_tokens)
_mark_lcs(
hit_mask,
lcs_dirs,
len(reference_sentence_tokens),
len(evaluated_sentence_tokens),
)
overlapping_count_length = 0
for ref_token_id, val in enumerate(hit_mask):
if val == 1:
token = reference_sentence_tokens[ref_token_id]
if evaluated_unigrams_dict[token] > 0 and reference_unigrams_dict[token] > 0:
evaluated_unigrams_dict[token] -= 1
reference_unigrams_dict[ref_token_id] -= 1
if use_WLCS:
overlapping_count_length += 1
if (
ref_token_id + 1 < len(hit_mask) and hit_mask[ref_token_id + 1] == 0
) or ref_token_id + 1 == len(hit_mask):
overlapping_count += overlapping_count_length ** weight_factor
overlapping_count_length = 0
else:
overlapping_count += 1
if use_WLCS:
reference_count = reference_count ** weight_factor
return evaluated_count, reference_count, overlapping_count
def get_scores(self, hypothesis, references):
if isinstance(hypothesis, str):
hypothesis, references = [hypothesis], [references]
if type(hypothesis) != type(references):
raise ValueError("'hyps' and 'refs' are not of the same type")
if len(hypothesis) != len(references):
raise ValueError("'hyps' and 'refs' do not have the same length")
scores = {}
has_rouge_n_metric = (
len([metric for metric in self.metrics if metric.split("-")[-1].isdigit()]) > 0
)
if has_rouge_n_metric:
scores.update(self._get_scores_rouge_n(hypothesis, references))
# scores = {**scores, **self._get_scores_rouge_n(hypothesis, references)}
has_rouge_l_metric = (
len([metric for metric in self.metrics if metric.split("-")[-1].lower() == "l"]) > 0
)
if has_rouge_l_metric:
scores.update(self._get_scores_rouge_l_or_w(hypothesis, references, False))
# scores = {**scores, **self._get_scores_rouge_l_or_w(hypothesis, references, False)}
has_rouge_w_metric = (
len([metric for metric in self.metrics if metric.split("-")[-1].lower() == "w"]) > 0
)
if has_rouge_w_metric:
scores.update(self._get_scores_rouge_l_or_w(hypothesis, references, True))
# scores = {**scores, **self._get_scores_rouge_l_or_w(hypothesis, references, True)}
return scores
def _get_scores_rouge_n(self, all_hypothesis, all_references):
metrics = [metric for metric in self.metrics if metric.split("-")[-1].isdigit()]
if self.apply_avg or self.apply_best:
scores = {metric: {stat: 0.0 for stat in Rouge.STATS} for metric in metrics}
else:
scores = {
metric: [{stat: [] for stat in Rouge.STATS} for _ in range(len(all_hypothesis))]
for metric in metrics
}
for sample_id, (hypothesis, references) in enumerate(zip(all_hypothesis, all_references)):
assert isinstance(hypothesis, str)
has_multiple_references = False
if isinstance(references, list):
has_multiple_references = len(references) > 1
if not has_multiple_references:
references = references[0]
# Prepare hypothesis and reference(s)
hypothesis = self._preprocess_summary_as_a_whole(hypothesis)
references = (
[self._preprocess_summary_as_a_whole(reference) for reference in references]
if has_multiple_references
else [self._preprocess_summary_as_a_whole(references)]
)
# Compute scores
for metric in metrics:
suffix = metric.split("-")[-1]
n = int(suffix)
# Aggregate
if self.apply_avg:
# average model
total_hypothesis_ngrams_count = 0
total_reference_ngrams_count = 0
total_ngrams_overlapping_count = 0
for reference in references:
(
hypothesis_count,
reference_count,
overlapping_ngrams,
) = Rouge._compute_ngrams(hypothesis, reference, n)
total_hypothesis_ngrams_count += hypothesis_count
total_reference_ngrams_count += reference_count
total_ngrams_overlapping_count += overlapping_ngrams
score = Rouge._compute_p_r_f_score(
total_hypothesis_ngrams_count,
total_reference_ngrams_count,
total_ngrams_overlapping_count,
self.alpha,
)
for stat in Rouge.STATS:
scores[metric][stat] += score[stat]
else:
# Best model
if self.apply_best:
best_current_score = None
for reference in references:
(
hypothesis_count,
reference_count,
overlapping_ngrams,
) = Rouge._compute_ngrams(hypothesis, reference, n)
score = Rouge._compute_p_r_f_score(
hypothesis_count,
reference_count,
overlapping_ngrams,
self.alpha,
)
if best_current_score is None or score["r"] > best_current_score["r"]:
best_current_score = score
for stat in Rouge.STATS:
scores[metric][stat] += best_current_score[stat]
# Keep all
else:
for reference in references:
(
hypothesis_count,
reference_count,
overlapping_ngrams,
) = Rouge._compute_ngrams(hypothesis, reference, n)
score = Rouge._compute_p_r_f_score(
hypothesis_count,
reference_count,
overlapping_ngrams,
self.alpha,
)
for stat in Rouge.STATS:
scores[metric][sample_id][stat].append(score[stat])
# Compute final score with the average or the the max
if (self.apply_avg or self.apply_best) and len(all_hypothesis) > 1:
for metric in metrics:
for stat in Rouge.STATS:
scores[metric][stat] /= len(all_hypothesis)
return scores
def _get_scores_rouge_l_or_w(self, all_hypothesis, all_references, use_w=False):
metric = "rouge-w" if use_w else "rouge-l"
if self.apply_avg or self.apply_best:
scores = {metric: {stat: 0.0 for stat in Rouge.STATS}}
else:
scores = {
metric: [{stat: [] for stat in Rouge.STATS} for _ in range(len(all_hypothesis))]
}
for sample_id, (hypothesis_sentences, references_sentences) in enumerate(
zip(all_hypothesis, all_references)
):
assert isinstance(hypothesis_sentences, str)
has_multiple_references = False
if isinstance(references_sentences, list):
has_multiple_references = len(references_sentences) > 1
if not has_multiple_references:
references_sentences = references_sentences[0]
# Prepare hypothesis and reference(s)
hypothesis_sentences = self._preprocess_summary_per_sentence(hypothesis_sentences)
references_sentences = (
[
self._preprocess_summary_per_sentence(reference)
for reference in references_sentences
]
if has_multiple_references
else [self._preprocess_summary_per_sentence(references_sentences)]
)
# Compute scores
# Aggregate
if self.apply_avg:
# average model
total_hypothesis_ngrams_count = 0
total_reference_ngrams_count = 0
total_ngrams_overlapping_count = 0
for reference_sentences in references_sentences:
(
hypothesis_count,
reference_count,
overlapping_ngrams,
) = Rouge._compute_ngrams_lcs(
hypothesis_sentences,
reference_sentences,
self.weight_factor if use_w else 1.0,
)
total_hypothesis_ngrams_count += hypothesis_count
total_reference_ngrams_count += reference_count
total_ngrams_overlapping_count += overlapping_ngrams
score = Rouge._compute_p_r_f_score(
total_hypothesis_ngrams_count,
total_reference_ngrams_count,
total_ngrams_overlapping_count,
self.alpha,
self.weight_factor if use_w else 1.0,
)
for stat in Rouge.STATS:
scores[metric][stat] += score[stat]
else:
# Best model
if self.apply_best:
best_current_score = None
best_current_score_wlcs = None
for reference_sentences in references_sentences:
(
hypothesis_count,
reference_count,
overlapping_ngrams,
) = Rouge._compute_ngrams_lcs(
hypothesis_sentences,
reference_sentences,
self.weight_factor if use_w else 1.0,
)
score = Rouge._compute_p_r_f_score(
total_hypothesis_ngrams_count,
total_reference_ngrams_count,
total_ngrams_overlapping_count,
self.alpha,
self.weight_factor if use_w else 1.0,
)
if use_w:
reference_count_for_score = reference_count ** (
1.0 / self.weight_factor
)
overlapping_ngrams_for_score = overlapping_ngrams
score_wlcs = (
overlapping_ngrams_for_score / reference_count_for_score
) ** (1.0 / self.weight_factor)
if (
best_current_score_wlcs is None
or score_wlcs > best_current_score_wlcs
):
best_current_score = score
best_current_score_wlcs = score_wlcs
else:
if best_current_score is None or score["r"] > best_current_score["r"]:
best_current_score = score
for stat in Rouge.STATS:
scores[metric][stat] += best_current_score[stat]
# Keep all
else:
for reference_sentences in references_sentences:
(
hypothesis_count,
reference_count,
overlapping_ngrams,
) = Rouge._compute_ngrams_lcs(
hypothesis_sentences,
reference_sentences,
self.weight_factor if use_w else 1.0,
)
score = Rouge._compute_p_r_f_score(
hypothesis_count,
reference_count,
overlapping_ngrams,
self.alpha,
self.weight_factor,
)
for stat in Rouge.STATS:
scores[metric][sample_id][stat].append(score[stat])
# Compute final score with the average or the the max
if (self.apply_avg or self.apply_best) and len(all_hypothesis) > 1:
for stat in Rouge.STATS:
scores[metric][stat] /= len(all_hypothesis)
return scores
def _preprocess_summary_as_a_whole(self, summary):
sentences = Rouge.split_into_sentences(summary)
# Truncate
if self.limit_length:
# By words
if self.length_limit_type == "words":
summary = " ".join(sentences)
all_tokens = summary.split() # Counting as in the perls script
summary = " ".join(all_tokens[: self.length_limit])
# By bytes
elif self.length_limit_type == "bytes":
summary = ""
current_len = 0
for sentence in sentences:
sentence = sentence.strip()
sentence_len = len(sentence)
if current_len + sentence_len < self.length_limit:
if current_len != 0:
summary += " "
summary += sentence
current_len += sentence_len
else:
if current_len > 0:
summary += " "
summary += sentence[: self.length_limit - current_len]
break
else:
summary = " ".join(sentences)
summary = Rouge.REMOVE_CHAR_PATTERN.sub(" ", summary.lower()).strip()
tokens = self.tokenize_text(Rouge.REMOVE_CHAR_PATTERN.sub(" ", summary))
preprocessed_summary = [" ".join(tokens)]
return preprocessed_summary
def _preprocess_summary_per_sentence(self, summary):
sentences = Rouge.split_into_sentences(summary)
# Truncate
if self.limit_length:
final_sentences = []
current_len = 0
# By words
if self.length_limit_type == "words":
for sentence in sentences:
tokens = sentence.strip().split()
tokens_len = len(tokens)
if current_len + tokens_len < self.length_limit:
sentence = " ".join(tokens)
final_sentences.append(sentence)
current_len += tokens_len
else:
sentence = " ".join(tokens[: self.length_limit - current_len])
final_sentences.append(sentence)
break
# By bytes
elif self.length_limit_type == "bytes":
for sentence in sentences:
sentence = sentence.strip()
sentence_len = len(sentence)
if current_len + sentence_len < self.length_limit:
final_sentences.append(sentence)
current_len += sentence_len
else:
sentence = sentence[: self.length_limit - current_len]
final_sentences.append(sentence)
break
sentences = final_sentences
final_sentences = []
for sentence in sentences:
sentence = Rouge.REMOVE_CHAR_PATTERN.sub(" ", sentence.lower()).strip()
tokens = self.tokenize_text(Rouge.REMOVE_CHAR_PATTERN.sub(" ", sentence))
sentence = " ".join(tokens)
final_sentences.append(sentence)
return final_sentences