SemF1 / semf1.py
nbansal's picture
Resolve the error with model_type
4c522b3
raw
history blame
8.03 kB
# 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}