|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
""" Word Error Ratio (WER) metric. """ |
|
|
|
import datasets |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
"""This module provides functions to calculate error rate in different level. |
|
e.g. wer for word-level, cer for char-level. |
|
""" |
|
import numpy as np |
|
|
|
|
|
|
|
def _levenshtein_distance(ref, hyp): |
|
"""Levenshtein distance is a string metric for measuring the difference |
|
between two sequences. Informally, the levenshtein disctance is defined as |
|
the minimum number of single-character edits (substitutions, insertions or |
|
deletions) required to change one word into the other. We can naturally |
|
extend the edits to word level when calculate levenshtein disctance for |
|
two sentences. |
|
""" |
|
m = len(ref) |
|
n = len(hyp) |
|
|
|
|
|
if ref == hyp: |
|
return 0 |
|
if m == 0: |
|
return n |
|
if n == 0: |
|
return m |
|
|
|
if m < n: |
|
ref, hyp = hyp, ref |
|
m, n = n, m |
|
|
|
|
|
distance = np.zeros((2, n + 1), dtype=np.int32) |
|
|
|
|
|
for j in range(n + 1): |
|
distance[0][j] = j |
|
|
|
|
|
for i in range(1, m + 1): |
|
prev_row_idx = (i - 1) % 2 |
|
cur_row_idx = i % 2 |
|
distance[cur_row_idx][0] = i |
|
for j in range(1, n + 1): |
|
if ref[i - 1] == hyp[j - 1]: |
|
distance[cur_row_idx][j] = distance[prev_row_idx][j - 1] |
|
else: |
|
s_num = distance[prev_row_idx][j - 1] + 1 |
|
i_num = distance[cur_row_idx][j - 1] + 1 |
|
d_num = distance[prev_row_idx][j] + 1 |
|
distance[cur_row_idx][j] = min(s_num, i_num, d_num) |
|
|
|
return distance[m % 2][n] |
|
|
|
|
|
def word_errors(reference, hypothesis, ignore_case=False, delimiter=' '): |
|
"""Compute the levenshtein distance between reference sequence and |
|
hypothesis sequence in word-level. |
|
|
|
:param reference: The reference sentence. |
|
:type reference: str |
|
:param hypothesis: The hypothesis sentence. |
|
:type hypothesis: str |
|
:param ignore_case: Whether case-sensitive or not. |
|
:type ignore_case: bool |
|
:param delimiter: Delimiter of input sentences. |
|
:type delimiter: char |
|
:return: Levenshtein distance and word number of reference sentence. |
|
:rtype: list |
|
""" |
|
if ignore_case == True: |
|
reference = reference.lower() |
|
hypothesis = hypothesis.lower() |
|
|
|
ref_words = list(filter(None, reference.split(delimiter))) |
|
hyp_words = list(filter(None, hypothesis.split(delimiter))) |
|
|
|
edit_distance = _levenshtein_distance(ref_words, hyp_words) |
|
return float(edit_distance), len(ref_words) |
|
|
|
|
|
def char_errors(reference, hypothesis, ignore_case=False, remove_space=False): |
|
"""Compute the levenshtein distance between reference sequence and |
|
hypothesis sequence in char-level. |
|
|
|
:param reference: The reference sentence. |
|
:type reference: str |
|
:param hypothesis: The hypothesis sentence. |
|
:type hypothesis: str |
|
:param ignore_case: Whether case-sensitive or not. |
|
:type ignore_case: bool |
|
:param remove_space: Whether remove internal space characters |
|
:type remove_space: bool |
|
:return: Levenshtein distance and length of reference sentence. |
|
:rtype: list |
|
""" |
|
if ignore_case == True: |
|
reference = reference.lower() |
|
hypothesis = hypothesis.lower() |
|
|
|
join_char = ' ' |
|
if remove_space == True: |
|
join_char = '' |
|
|
|
reference = join_char.join(list(filter(None, reference.split(' ')))) |
|
hypothesis = join_char.join(list(filter(None, hypothesis.split(' ')))) |
|
|
|
edit_distance = _levenshtein_distance(reference, hypothesis) |
|
return float(edit_distance), len(reference) |
|
|
|
|
|
def cer(reference, hypothesis, ignore_case=False, remove_space=True): |
|
"""Calculate charactor error rate (CER). CER compares reference text and |
|
hypothesis text in char-level. CER is defined as: |
|
|
|
.. math:: |
|
CER = (Sc + Dc + Ic) / Nc |
|
|
|
where |
|
|
|
.. code-block:: text |
|
|
|
Sc is the number of characters substituted, |
|
Dc is the number of characters deleted, |
|
Ic is the number of characters inserted |
|
Nc is the number of characters in the reference |
|
|
|
We can use levenshtein distance to calculate CER. Chinese input should be |
|
encoded to unicode. Please draw an attention that the leading and tailing |
|
space characters will be truncated and multiple consecutive space |
|
characters in a sentence will be replaced by one space character. |
|
|
|
:param reference: The reference sentence. |
|
:type reference: str |
|
:param hypothesis: The hypothesis sentence. |
|
:type hypothesis: str |
|
:param ignore_case: Whether case-sensitive or not. |
|
:type ignore_case: bool |
|
:param remove_space: Whether remove internal space characters |
|
:type remove_space: bool |
|
:return: Character error rate. |
|
:rtype: float |
|
:raises ValueError: If the reference length is zero. |
|
""" |
|
edit_distance, ref_len = char_errors(reference, hypothesis, ignore_case, |
|
remove_space) |
|
|
|
if ref_len == 0: |
|
raise ValueError("Length of reference should be greater than 0.") |
|
|
|
cer = float(edit_distance) / ref_len |
|
return edit_distance, ref_len, cer |
|
|
|
|
|
|
|
_CITATION = """\ |
|
@inproceedings{inproceedings, |
|
author = {Morris, Andrew and Maier, Viktoria and Green, Phil}, |
|
year = {2004}, |
|
month = {01}, |
|
pages = {}, |
|
title = {From WER and RIL to MER and WIL: improved evaluation measures for connected speech recognition.} |
|
} |
|
""" |
|
|
|
_DESCRIPTION = """\ |
|
Word error rate (WER) is a common metric of the performance of an automatic speech recognition system. |
|
|
|
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. |
|
|
|
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. |
|
|
|
Word error rate can then be computed as: |
|
|
|
WER = (S + D + I) / N = (S + D + I) / (S + D + C) |
|
|
|
where |
|
|
|
S is the number of substitutions, |
|
D is the number of deletions, |
|
I is the number of insertions, |
|
C is the number of correct words, |
|
N is the number of words in the reference (N=S+D+C). |
|
|
|
WER's output is always a number between 0 and 1. This value indicates the percentage of words that were incorrectly predicted. The lower the value, the better the |
|
performance of the ASR system with a WER of 0 being a perfect score. |
|
""" |
|
|
|
_KWARGS_DESCRIPTION = """ |
|
Computes WER score of transcribed segments against references. |
|
Args: |
|
references: list of references for each speech input. |
|
predictions: list of transcribtions to score. |
|
Returns: |
|
(float): the word error rate |
|
|
|
Examples: |
|
|
|
>>> predictions = ["this is the prediction", "there is an other sample"] |
|
>>> references = ["this is the reference", "there is another one"] |
|
>>> wer = datasets.load_metric("wer") |
|
>>> wer_score = wer.compute(predictions=predictions, references=references) |
|
>>> print(wer_score) |
|
0.5 |
|
""" |
|
|
|
|
|
@datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION, _KWARGS_DESCRIPTION) |
|
class CER(datasets.Metric): |
|
def _info(self): |
|
return datasets.MetricInfo( |
|
description=_DESCRIPTION, |
|
citation=_CITATION, |
|
inputs_description=_KWARGS_DESCRIPTION, |
|
features=datasets.Features( |
|
{ |
|
"predictions": datasets.Value("string", id="sequence"), |
|
"references": datasets.Value("string", id="sequence"), |
|
} |
|
), |
|
codebase_urls=["https://github.com/jitsi/jiwer/"], |
|
reference_urls=[ |
|
"https://en.wikipedia.org/wiki/Word_error_rate", |
|
], |
|
) |
|
|
|
def _compute(self, predictions, references): |
|
total_edit_distance, total_ref_len = 0, 0 |
|
for pred, ref in zip(predictions, references): |
|
edit_distance, ref_len, _ = cer(ref, pred) |
|
total_edit_distance += edit_distance |
|
total_ref_len += ref_len |
|
return total_edit_distance / total_ref_len |
|
|