datasets

Форк
0
105 строк · 4.4 Кб
1
# Copyright 2021 The HuggingFace Datasets Authors.
2
#
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
6
#
7
#     http://www.apache.org/licenses/LICENSE-2.0
8
#
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
"""Word Error Ratio (WER) metric."""
15

16
from jiwer import compute_measures
17

18
import datasets
19

20

21
_CITATION = """\
22
@inproceedings{inproceedings,
23
    author = {Morris, Andrew and Maier, Viktoria and Green, Phil},
24
    year = {2004},
25
    month = {01},
26
    pages = {},
27
    title = {From WER and RIL to MER and WIL: improved evaluation measures for connected speech recognition.}
28
}
29
"""
30

31
_DESCRIPTION = """\
32
Word error rate (WER) is a common metric of the performance of an automatic speech recognition system.
33

34
The general difficulty of measuring performance lies in the fact that the recognized word sequence can have a different length from the reference word sequence (supposedly the correct one). The WER is derived from the Levenshtein distance, working at the word level instead of the phoneme level. The WER is a valuable tool for comparing different systems as well as for evaluating improvements within one system. This kind of measurement, however, provides no details on the nature of translation errors and further work is therefore required to identify the main source(s) of error and to focus any research effort.
35

36
This problem is solved by first aligning the recognized word sequence with the reference (spoken) word sequence using dynamic string alignment. Examination of this issue is seen through a theory called the power law that states the correlation between perplexity and word error rate.
37

38
Word error rate can then be computed as:
39

40
WER = (S + D + I) / N = (S + D + I) / (S + D + C)
41

42
where
43

44
S is the number of substitutions,
45
D is the number of deletions,
46
I is the number of insertions,
47
C is the number of correct words,
48
N is the number of words in the reference (N=S+D+C).
49

50
This value indicates the average number of errors per reference word. The lower the value, the better the
51
performance of the ASR system with a WER of 0 being a perfect score.
52
"""
53

54
_KWARGS_DESCRIPTION = """
55
Compute WER score of transcribed segments against references.
56

57
Args:
58
    references: List of references for each speech input.
59
    predictions: List of transcriptions to score.
60
    concatenate_texts (bool, default=False): Whether to concatenate all input texts or compute WER iteratively.
61

62
Returns:
63
    (float): the word error rate
64

65
Examples:
66

67
    >>> predictions = ["this is the prediction", "there is an other sample"]
68
    >>> references = ["this is the reference", "there is another one"]
69
    >>> wer = datasets.load_metric("wer")
70
    >>> wer_score = wer.compute(predictions=predictions, references=references)
71
    >>> print(wer_score)
72
    0.5
73
"""
74

75

76
@datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION, _KWARGS_DESCRIPTION)
77
class WER(datasets.Metric):
78
    def _info(self):
79
        return datasets.MetricInfo(
80
            description=_DESCRIPTION,
81
            citation=_CITATION,
82
            inputs_description=_KWARGS_DESCRIPTION,
83
            features=datasets.Features(
84
                {
85
                    "predictions": datasets.Value("string", id="sequence"),
86
                    "references": datasets.Value("string", id="sequence"),
87
                }
88
            ),
89
            codebase_urls=["https://github.com/jitsi/jiwer/"],
90
            reference_urls=[
91
                "https://en.wikipedia.org/wiki/Word_error_rate",
92
            ],
93
        )
94

95
    def _compute(self, predictions=None, references=None, concatenate_texts=False):
96
        if concatenate_texts:
97
            return compute_measures(references, predictions)["wer"]
98
        else:
99
            incorrect = 0
100
            total = 0
101
            for prediction, reference in zip(predictions, references):
102
                measures = compute_measures(reference, prediction)
103
                incorrect += measures["substitutions"] + measures["deletions"] + measures["insertions"]
104
                total += measures["substitutions"] + measures["deletions"] + measures["hits"]
105
            return incorrect / total
106

Использование cookies

Мы используем файлы cookie в соответствии с Политикой конфиденциальности и Политикой использования cookies.

Нажимая кнопку «Принимаю», Вы даете АО «СберТех» согласие на обработку Ваших персональных данных в целях совершенствования нашего веб-сайта и Сервиса GitVerse, а также повышения удобства их использования.

Запретить использование cookies Вы можете самостоятельно в настройках Вашего браузера.