keywords_evaluate / keywords_evaluate.py
Rodrigo Ferreira Rodrigues
Correcting bug
e0f7547
# 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 a description here."""
import evaluate
import datasets
import re
# TODO: Add BibTeX citation
_CITATION = """\
@InProceedings{huggingface:module,
title = {A great new module},
authors={huggingface, Inc.},
year={2020}
}
"""
# TODO: Add description of the module here
_DESCRIPTION = """\
This metric aims to evaluate LM generations where it has to predict one or multiple keywords.
"""
# TODO: Add description of the arguments of the module here
_KWARGS_DESCRIPTION = """
Calculates Accuracy between generations and gold answers in a Keyword generation context.
Args:
generations: list of predictions to score. Each predictions
should be a string generated by a LM model.
golds: list of reference for each prediction. Each
reference should be a list of strings only. Each string should be a keyword.
Returns:
accuracy: 1 if the set of keywords generated matches the set of gold ones in case strict is True. If strict is False, only one keyword from the set generated must match at least one gold keyword. 0 otherwise.
Examples:
Here is an exemple on how to use the metric:
>>> metric = evaluate.load("rfr2003/keywords_evaluate")
>>> results = metric.compute(generations=["yes", "no"], golds=[["yes"], ["yes"]], keywords=['yes', 'no'])
>>> print(results)
{'accuracy': 0.5}
"""
@evaluate.utils.file_utils.add_start_docstrings(_DESCRIPTION, _KWARGS_DESCRIPTION)
class Keywords_evaluate(evaluate.Metric):
"""TODO: Short description of my evaluation module."""
def _info(self):
# TODO: Specifies the evaluate.EvaluationModuleInfo object
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({
'generations': datasets.Value('string'),
'golds': datasets.Sequence(datasets.Value('string')),
}),
)
def _download_and_prepare(self, dl_manager):
"""Optional: download external resources useful to compute the scores"""
# TODO: Download external resources if needed
pass
def _compute(self, generations, golds, keywords=['yes', 'no'], strict=True):
'''Calculate Accuracy scores between model generations and golden answers where the task is to generate the good(s) keyword(s) among a list of them. If strict is True, we expect to find all the expected keywords generated, if not we want only one'''
assert len(generations) == len(golds)
assert isinstance(golds, list)
correct, total = 0, 0
if keywords:
keywords = set(keywords)
pattern = r"\b(" + "|".join(map(re.escape, keywords)) + r")\b"
else:
subs = ['[', ']', '(', ')', ' ']
pattern = r'(' + '|'.join(map(re.escape, subs)) + r')'
for gen, gold in zip(generations, golds):
#each gold must be a list
for i in range(len(gold)):
gold[i] = str(gold[i]).lower().strip()
if keywords:
find = re.findall(pattern, gen.strip().lower())
else:
find = re.sub(pattern, "", gen).split(',')
f_gold = set(gold)
if strict:
f_ans = set(find)
if f_ans == f_gold:
correct += 1
else:
f_ans = find[0]
for i in range(len(gold)):
if f_ans == gold[i]:
correct += 1
f_gold = gold[i]
total += 1
metrics = {}
metrics.update({
'accuracy': correct/total,
})
return metrics