File size: 8,026 Bytes
f036197
 
 
 
 
 
 
 
 
 
 
 
 
90d2f63
 
f036197
 
90d2f63
 
 
 
 
 
 
 
 
 
f036197
 
90d2f63
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f036197
 
 
 
90d2f63
 
 
f036197
 
 
90d2f63
 
f036197
90d2f63
 
f036197
90d2f63
 
 
 
 
f036197
 
 
 
 
90d2f63
 
 
 
 
 
 
 
 
 
 
 
 
f036197
 
4c522b3
90d2f63
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f036197
 
 
 
90d2f63
 
 
 
 
f036197
 
 
 
 
 
 
 
 
 
90d2f63
 
f036197
90d2f63
f036197
90d2f63
f036197
 
90d2f63
 
4c522b3
 
 
90d2f63
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f036197
90d2f63
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
# Copyright 2020 The HuggingFace Datasets Authors and the current dataset script contributor.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# TODO: Add test cases
"""SEM-F1 metric"""


import abc
import sys
from typing import List, Optional, Tuple

import datasets
import evaluate
import numpy as np
from numpy.typing import NDArray
from sentence_transformers import SentenceTransformer
from sklearn.metrics.pairwise import cosine_similarity

_CITATION = """\
@inproceedings{bansal-etal-2022-sem,
    title = "{SEM}-F1: an Automatic Way for Semantic Evaluation of Multi-Narrative Overlap Summaries at Scale",
    author = "Bansal, Naman  and
      Akter, Mousumi  and
      Karmaker Santu, Shubhra Kanti",
    editor = "Goldberg, Yoav  and
      Kozareva, Zornitsa  and
      Zhang, Yue",
    booktitle = "Proceedings of the 2022 Conference on Empirical Methods in Natural Language Processing",
    month = dec,
    year = "2022",
    address = "Abu Dhabi, United Arab Emirates",
    publisher = "Association for Computational Linguistics",
    url = "https://aclanthology.org/2022.emnlp-main.49",
    doi = "10.18653/v1/2022.emnlp-main.49",
    pages = "780--792",
    abstract = "Recent work has introduced an important yet relatively under-explored NLP task called Semantic Overlap Summarization (SOS) that entails generating a summary from multiple alternative narratives which conveys the common information provided by those narratives. Previous work also published a benchmark dataset for this task by collecting 2,925 alternative narrative pairs from the web and manually annotating 411 different reference summaries by engaging human annotators. In this paper, we exclusively focus on the automated evaluation of the SOS task using the benchmark dataset. More specifically, we first use the popular ROUGE metric from text-summarization literature and conduct a systematic study to evaluate the SOS task. Our experiments discover that ROUGE is not suitable for this novel task and therefore, we propose a new sentence-level precision-recall style automated evaluation metric, called SEM-F1 (Semantic F1). It is inspired by the benefits of the sentence-wise annotation technique using overlap labels reported by the previous work. Our experiments show that the proposed SEM-F1 metric yields a higher correlation with human judgment and higher inter-rater agreement compared to the ROUGE metric.",
}
"""

_DESCRIPTION = """\
SEM-F1 metric leverages the pre-trained contextual embeddings and evaluates the model generated 
semantic overlap summary with the reference overlap summary. It evaluates the semantic overlap summary at the 
sentence level and computes precision, recall and F1 scores.
"""

_KWARGS_DESCRIPTION = """
SEM-F1 compares the system generated overlap summary with ground truth reference overlap.

Args:
    predictions: List[List(str)] - List of  predictions where each prediction is a list of sentences.
    references: List[List(str)] - List of references where each reference is a list of sentences.
        reference should be a string with tokens separated by spaces.
    model_type: str - Model to use. [pv1, stsb, use] 
        Options: 
            pv1 - paraphrase-distilroberta-base-v1 
            stsb - stsb-roberta-large 
            use - Universal Sentence Encoder
Returns:
    accuracy: description of the first score,
    another_score: description of the second score,
Examples:

    >>> import evaluate
    >>> predictions = [
        ["I go to School.", "You are stupid."],
        ["I love adventure sports."],
    ]
    >>> references = [
        ["I go to School.", "You are stupid."],
        ["I love adventure sports."],
    ]
    >>> metric = evaluate.load("semf1")
    >>> results = metric.compute(predictions=predictions, references=references)
    >>> print([round(v, 2) for v in results["f1"]])
    [0.77, 0.56]
"""

[["I go to School.", "You are stupid."]]

class Encoder(metaclass=abc.ABCMeta):
    @abc.abstractmethod
    def encode(self, prediction: List[str]) -> NDArray:
        pass


class USE(Encoder):
    def __init__(self):
        pass

    def encode(self, prediction: List[str]) -> NDArray:
        pass


class SBertEncoder(Encoder):
    def __init__(self, model_name: str):
        self.model = SentenceTransformer(model_name)

    def encode(self, prediction: List[str]) -> NDArray:
        return self.model.encode(prediction)


def _get_encoder(model_name: str):
    if model_name == "use":
        return USE()
    else:
        return SBertEncoder(model_name)


def _compute_f1(p, r, eps=sys.float_info.epsilon):
    '''
    Computes F1 value
    :param p: Precision Value
    :param r: Recall Value
    :return:
    '''
    f1 = 2 * p * r / (p + r + eps)
    return f1


def _compute_cosine_similarity(pred_embeds: NDArray, ref_embeds: NDArray) -> Tuple[float, float]:
    cosine_scores = cosine_similarity(pred_embeds, ref_embeds)
    precision_per_sentence_sim = np.max(cosine_scores, axis=-1)
    recall_per_sentence_sim = np.max(cosine_scores, axis=0)
    return np.mean(precision_per_sentence_sim).item(), np.mean(recall_per_sentence_sim).item()


@evaluate.utils.file_utils.add_start_docstrings(_DESCRIPTION, _KWARGS_DESCRIPTION)
class SemF1(evaluate.Metric):
    _MODEL_TYPE_TO_NAME = {
        "pv1": "paraphrase-distilroberta-base-v1",
        "stsb": "stsb-roberta-large",
        "use": "use",
    }

    def _info(self):
        return evaluate.MetricInfo(
            # This is the description that will appear on the modules page.
            module_type="metric",
            description=_DESCRIPTION,
            citation=_CITATION,
            inputs_description=_KWARGS_DESCRIPTION,
            # This defines the format of each prediction and reference
            features=datasets.Features({
                'predictions': datasets.Sequence(datasets.Value("string", id="sequence"), id="predictions"),
                'references': datasets.Sequence(datasets.Value("string", id="sequence"), id="references"),
            }),
            # # Homepage of the module for documentation
            # Additional links to the codebase or references
            reference_urls=["https://aclanthology.org/2022.emnlp-main.49/"]
        )

    def _get_model_name(self, model_type: Optional[str] = None) -> str:
        # TODO: make it work with USE as well
        if model_type is None:
            model_type = "pv1"  # Change it to use

        if model_type not in self._MODEL_TYPE_TO_NAME.keys():
            raise ValueError(f"Provide a correct model_type.\n"
                             f"Options: {self._MODEL_TYPE_TO_NAME.keys()}\n"
                             f"Currently provided: {model_type}")

        return self._MODEL_TYPE_TO_NAME[model_type]

    def _compute(self, predictions, references, model_type: Optional[str] = None):
        model_name = self._get_model_name(model_type)
        encoder = _get_encoder(model_name)

        precisions = [0] * len(predictions)
        recalls = [0] * len(predictions)
        f1_scores = [0] * len(predictions)

        for idx, (preds, refs) in enumerate(zip(predictions, references)):
            pred_embeddings = encoder.encode(preds)
            ref_embeddings = encoder.encode(refs)
            p, r = _compute_cosine_similarity(pred_embeddings, ref_embeddings)
            f1 = _compute_f1(p, r)
            precisions[idx] = p
            recalls[idx] = r
            f1_scores[idx] = f1

        return {"precision": precisions, "recall": recalls, "f1": f1_scores}