1
# Copyright 2021 The HuggingFace Datasets Authors.
3
# Licensed under the Apache License, Version 2.0 (the "License");
4
# you may not use this file except in compliance with the License.
5
# You may obtain a copy of the License at
7
# http://www.apache.org/licenses/LICENSE-2.0
9
# Unless required by applicable law or agreed to in writing, software
10
# distributed under the License is distributed on an "AS IS" BASIS,
11
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
# See the License for the specific language governing permissions and
13
# limitations under the License.
14
"""Chrf(++) metric as available in sacrebleu."""
16
import sacrebleu as scb
17
from packaging import version
18
from sacrebleu import CHRF
24
@inproceedings{popovic-2015-chrf,
25
title = "chr{F}: character n-gram {F}-score for automatic {MT} evaluation",
26
author = "Popovi{\'c}, Maja",
27
booktitle = "Proceedings of the Tenth Workshop on Statistical Machine Translation",
30
address = "Lisbon, Portugal",
31
publisher = "Association for Computational Linguistics",
32
url = "https://aclanthology.org/W15-3049",
33
doi = "10.18653/v1/W15-3049",
36
@inproceedings{popovic-2017-chrf,
37
title = "chr{F}++: words helping character n-grams",
38
author = "Popovi{\'c}, Maja",
39
booktitle = "Proceedings of the Second Conference on Machine Translation",
42
address = "Copenhagen, Denmark",
43
publisher = "Association for Computational Linguistics",
44
url = "https://aclanthology.org/W17-4770",
45
doi = "10.18653/v1/W17-4770",
48
@inproceedings{post-2018-call,
49
title = "A Call for Clarity in Reporting {BLEU} Scores",
50
author = "Post, Matt",
51
booktitle = "Proceedings of the Third Conference on Machine Translation: Research Papers",
54
address = "Belgium, Brussels",
55
publisher = "Association for Computational Linguistics",
56
url = "https://www.aclweb.org/anthology/W18-6319",
62
ChrF and ChrF++ are two MT evaluation metrics. They both use the F-score statistic for character n-gram matches,
63
and ChrF++ adds word n-grams as well which correlates more strongly with direct assessment. We use the implementation
64
that is already present in sacrebleu.
66
The implementation here is slightly different from sacrebleu in terms of the required input format. The length of
67
the references and hypotheses lists need to be the same, so you may need to transpose your references compared to
68
sacrebleu's required input format. See https://github.com/huggingface/datasets/issues/3154#issuecomment-950746534
70
See the README.md file at https://github.com/mjpost/sacreBLEU#chrf--chrf for more information.
73
_KWARGS_DESCRIPTION = """
74
Produces ChrF(++) scores for hypotheses given reference translations.
77
predictions (list of str): The predicted sentences.
78
references (list of list of str): The references. There should be one reference sub-list for each prediction sentence.
79
char_order (int): Character n-gram order. Defaults to `6`.
80
word_order (int): Word n-gram order. If equals to `2`, the metric is referred to as chrF++. Defaults to `0`.
81
beta (int): Determine the importance of recall w.r.t precision. Defaults to `2`.
82
lowercase (bool): if `True`, enables case-insensitivity. Defaults to `False`.
83
whitespace (bool): If `True`, include whitespaces when extracting character n-grams.
84
eps_smoothing (bool): If `True`, applies epsilon smoothing similar
85
to reference chrF++.py, NLTK and Moses implementations. If `False`,
86
it takes into account effective match order similar to sacreBLEU < 2.0.0. Defaults to `False`.
89
'score' (float): The chrF (chrF++) score,
90
'char_order' (int): The character n-gram order,
91
'word_order' (int): The word n-gram order. If equals to 2, the metric is referred to as chrF++,
92
'beta' (int): Determine the importance of recall w.r.t precision
95
Example 1--a simple example of calculating chrF:
96
>>> prediction = ["The relationship between cats and dogs is not exactly friendly.", "a good bookshop is just a genteel black hole that knows how to read."]
97
>>> reference = [["The relationship between dogs and cats is not exactly friendly."], ["A good bookshop is just a genteel Black Hole that knows how to read."]]
98
>>> chrf = datasets.load_metric("chrf")
99
>>> results = chrf.compute(predictions=prediction, references=reference)
101
{'score': 84.64214891738334, 'char_order': 6, 'word_order': 0, 'beta': 2}
103
Example 2--the same example, but with the argument word_order=2, to calculate chrF++ instead of chrF:
104
>>> prediction = ["The relationship between cats and dogs is not exactly friendly.", "a good bookshop is just a genteel black hole that knows how to read."]
105
>>> reference = [["The relationship between dogs and cats is not exactly friendly."], ["A good bookshop is just a genteel Black Hole that knows how to read."]]
106
>>> chrf = datasets.load_metric("chrf")
107
>>> results = chrf.compute(predictions=prediction,
108
... references=reference,
111
{'score': 82.87263732906315, 'char_order': 6, 'word_order': 2, 'beta': 2}
113
Example 3--the same chrF++ example as above, but with `lowercase=True` to normalize all case:
114
>>> prediction = ["The relationship between cats and dogs is not exactly friendly.", "a good bookshop is just a genteel black hole that knows how to read."]
115
>>> reference = [["The relationship between dogs and cats is not exactly friendly."], ["A good bookshop is just a genteel Black Hole that knows how to read."]]
116
>>> chrf = datasets.load_metric("chrf")
117
>>> results = chrf.compute(predictions=prediction,
118
... references=reference,
122
{'score': 92.12853119829202, 'char_order': 6, 'word_order': 2, 'beta': 2}
126
@datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION, _KWARGS_DESCRIPTION)
127
class ChrF(datasets.Metric):
129
if version.parse(scb.__version__) < version.parse("1.4.12"):
131
"To use `sacrebleu`, the module `sacrebleu>=1.4.12` is required, and the current version of `sacrebleu` doesn't match this condition.\n"
132
'You can install it with `pip install "sacrebleu>=1.4.12"`.'
134
return datasets.MetricInfo(
135
description=_DESCRIPTION,
137
homepage="https://github.com/mjpost/sacreBLEU#chrf--chrf",
138
inputs_description=_KWARGS_DESCRIPTION,
139
features=datasets.Features(
141
"predictions": datasets.Value("string", id="sequence"),
142
"references": datasets.Sequence(datasets.Value("string", id="sequence"), id="references"),
145
codebase_urls=["https://github.com/mjpost/sacreBLEU#chrf--chrf"],
147
"https://github.com/m-popovic/chrF",
155
char_order: int = CHRF.CHAR_ORDER,
156
word_order: int = CHRF.WORD_ORDER,
157
beta: int = CHRF.BETA,
158
lowercase: bool = False,
159
whitespace: bool = False,
160
eps_smoothing: bool = False,
162
references_per_prediction = len(references[0])
163
if any(len(refs) != references_per_prediction for refs in references):
164
raise ValueError("Sacrebleu requires the same number of references for each prediction")
165
transformed_references = [[refs[i] for refs in references] for i in range(references_per_prediction)]
167
sb_chrf = CHRF(char_order, word_order, beta, lowercase, whitespace, eps_smoothing)
168
output = sb_chrf.corpus_score(predictions, transformed_references)
171
"score": output.score,
172
"char_order": output.char_order,
173
"word_order": output.word_order,