Algorithm Search⌘K

Definitionintro

Word error rate

Also called WER.

The number of substitutions, deletions and insertions in the minimum edit alignment of hypothesis to reference, over reference length.

The word error rate (WER) measures how far the output of a speech recognizer is from a reference transcript. Align the hypothesis to the reference with the least number of word substitutions SS, deletions DD and insertions II, and divide that number by the number NN of words in the reference: WER=(S+D+I)/N\mathrm{WER} = (S + D + I) / N. The numerator is the word level edit distance, computed by the Wagner-Fischer algorithm. Lower is better, 0 means a perfect match, and the value can exceed 1.

Definition

Let the reference be r=r1…rNr = r_1 \ldots r_N with N≥1N \ge 1 and the hypothesis be h=h1…hMh = h_1 \ldots h_M with M≥0M \ge 0, both sequences of words after the same text normalization. An alignment of hh to rr is a sequence of operations that reads both sequences from left to right. Each operation is one of

  • a match or a substitution, which pairs rir_i with hjh_j (a substitution if ri≠hjr_i \ne h_j),
  • a deletion, which leaves rir_i without a partner in hh,
  • an insertion, which leaves hjh_j without a partner in rr.

The cost of an alignment is the number of substitutions, deletions and insertions, with cost 1 each. Let E(r,h)E(r, h) be the least cost of an alignment; this is the Levenshtein distance between the two sequences of words. Then

WER(r,h)=S+D+IN=E(r,h)N,\mathrm{WER}(r, h) = \frac{S + D + I}{N} = \frac{E(r, h)}{N},

where SS, DD and II are the counts of one alignment of least cost. The sum S+D+I=E(r,h)S + D + I = E(r, h) is the same for every alignment of least cost, but the split into SS, DD and II can differ between them. For example, r=(a,b)r = (a, b) and h=(b,a)h = (b, a) have E=2E = 2 by two substitutions, or by one deletion and one insertion. A scoring tool fixes a tie rule. The code of this page prefers a match or a substitution, then a deletion, then an insertion. Every alignment satisfies D−I=N−MD - I = N - M.

For a test set of utterances (r1,h1),…,(rK,hK)(r^1, h^1), \ldots, (r^K, h^K), the corpus WER is the total number of errors over the total number of reference words:

WER=∑kE(rk,hk)∑kNk.\mathrm{WER} = \frac{\sum_k E(r^k, h^k)}{\sum_k N_k}.

This is the number that papers report. It is not the mean of the sentence WERs. Word accuracy is 1−WER1 - \mathrm{WER}, and the word correct rate (N−S−D)/N(N - S - D)/N ignores insertions.

WER is undefined for an empty reference. The value depends on the text normalization: case, punctuation, numbers, hyphens, contractions and filler words must be handled the same way in the reference and the hypothesis, and the normalization is part of the definition of any reported number.

Examples and non-examples

  • One substitution and one deletion. rr = "the cat sat on the mat", hh = "the cat sit on mat". One alignment of least cost substitutes "sit" for "sat" and deletes the second "the". So S=1S = 1, D=1D = 1, I=0I = 0, N=6N = 6 and WER=2/6=1/3≈0.333333\mathrm{WER} = 2/6 = 1/3 \approx 0.333333.
  • Above 1. rr = "a b", hh = "x y z w". The best alignment has 2 substitutions and 2 insertions, so WER=4/2=2\mathrm{WER} = 4/2 = 2. A recognizer that outputs many extra words can have a WER above 100 percent. Similarly rr = "a" and hh = "a x y" give 2.
  • Empty output. If hh is empty, every reference word is deleted and WER=1\mathrm{WER} = 1. So a recognizer that outputs nothing beats one that outputs many wrong words.
  • Corpus against sentence average. Take one utterance "a" recognized as "b", and one of 9 words recognized without errors. The corpus WER is 1/101/10. The mean of the sentence WERs is (1+0)/2=1/2(1 + 0)/2 = 1/2, which gives the short utterance the same weight as the long one.
  • Normalization. rr = "The cat sat." and hh = "the cat sat" give WER=2/3\mathrm{WER} = 2/3 if the words are compared as written, because "The" and "sat." do not match. After lower casing and stripping the punctuation, the WER is 0.
  • Not a WER: the edit distance of the characters. The character error rate uses the same formula over characters. It is the usual measure for languages written without spaces between words, and it is not comparable with WER.
  • Not a WER: the sentence error rate. The fraction of utterances with at least one error ignores how many errors each one has.
  • Not a metric. WER divides by the length of the reference, so WER(r,h)≠WER(h,r)\mathrm{WER}(r, h) \ne \mathrm{WER}(h, r) in general. In the first example, WER(h,r)=2/5\mathrm{WER}(h, r) = 2/5.

The tests in the code check these values with exact fractions, and compare the alignment with a brute force recursion on random word sequences.

  • Edit distance. WER is the word level Levenshtein distance divided by the reference length. The Wagner-Fischer algorithm computes it in Θ(NM)\Theta(N M) time, and its traceback gives the alignment and the counts SS, DD and II.
  • Character, phone and token error rates. The same formula over characters, phones or subword tokens.
  • Expected WER. Decoders that output a confusion network or rescore a word lattice choose the hypothesis with the least expected number of word errors in place of the most probable word sequence.
  • Perplexity. A measure of a language model on text. Lower perplexity often goes with lower WER, but this is an observation about language models and not a rule, so WER is measured directly.
  • Significance of a difference. Two systems on the same test set are compared by tests on paired errors, such as the McNemar test on the utterances or the bootstrap method on the per utterance error counts. A small difference in WER on a small test set is often not significant.
  • Automatic speech recognition. WER is the main measure of this problem. A reported WER names its test set, for example the Wall Street Journal Nov'93 evaluation, where Young, Odell and Woodland 1994 reported 4.90 percent on the 5k task and 12.67 percent on the 20k task (measurements).

Code

Each implementation follows the pseudocode above. A comment @line links a line of code to a line of the pseudocode. Point at a line of the pseudocode to see the matching code. The build runs the native tests of each language.

word_error_rate.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/word-error-rate/. The authors are listed in prov/8WQ3ZQ.jsonl.

"""Word error rate: WER = (S + D + I) / N.

S, D and I are the substitutions, deletions and insertions of a minimum edit
alignment of the hypothesis to the reference with unit costs, and N is the
number of reference words. The edit distance is the Wagner-Fischer dynamic
program. Among the minimum alignments, the traceback prefers a match or a
substitution, then a deletion, then an insertion; the sum S + D + I is the same
for every minimum alignment, but the split into S, D and I can differ.
"""

from fractions import Fraction
from typing import List, Sequence, Tuple


def normalize(text: str) -> List[str]:
    """The normalization of this file: lower case, split on white space, and strip
    the punctuation . , ? ! ; : and double quotes at the ends of each word."""
    words = [w.strip('.,?!;:"') for w in text.lower().split()]
    return [w for w in words if w]


def align(ref: Sequence[str], hyp: Sequence[str]) -> Tuple[int, int, int, List[Tuple[str, str, str]]]:
    """Return (S, D, I, ops) of a minimum edit alignment. ops lists (op, ref word, hyp word)
    with op in "=", "S", "D", "I"; a missing word is ""."""
    n, m = len(ref), len(hyp)
    E = [[0] * (m + 1) for _ in range(n + 1)]
    for i in range(1, n + 1):
        E[i][0] = i
    for j in range(1, m + 1):
        E[0][j] = j
    for i in range(1, n + 1):
        for j in range(1, m + 1):
            sub = E[i - 1][j - 1] + (ref[i - 1] != hyp[j - 1])
            E[i][j] = min(sub, E[i - 1][j] + 1, E[i][j - 1] + 1)
    ops = []
    i, j = n, m
    while i > 0 or j > 0:
        if i > 0 and j > 0 and E[i][j] == E[i - 1][j - 1] + (ref[i - 1] != hyp[j - 1]):
            ops.append(("=" if ref[i - 1] == hyp[j - 1] else "S", ref[i - 1], hyp[j - 1]))
            i, j = i - 1, j - 1
        elif i > 0 and E[i][j] == E[i - 1][j] + 1:
            ops.append(("D", ref[i - 1], ""))
            i -= 1
        else:
            ops.append(("I", "", hyp[j - 1]))
            j -= 1
    ops.reverse()
    S = sum(op == "S" for op, _, _ in ops)
    D = sum(op == "D" for op, _, _ in ops)
    I = sum(op == "I" for op, _, _ in ops)
    assert S + D + I == E[n][m]
    return S, D, I, ops


def wer(ref: Sequence[str], hyp: Sequence[str]) -> Fraction:
    """Sentence WER as an exact fraction. Raise ValueError for an empty reference."""
    if not ref:
        raise ValueError("WER is undefined for an empty reference")
    S, D, I, _ = align(ref, hyp)
    return Fraction(S + D + I, len(ref))


def corpus_wer(pairs: Sequence[Tuple[Sequence[str], Sequence[str]]]) -> Fraction:
    """Corpus WER: the total errors over the total reference words (not the mean of sentence WERs)."""
    errors = words = 0
    for ref, hyp in pairs:
        S, D, I, _ = align(ref, hyp)
        errors += S + D + I
        words += len(ref)
    if words == 0:
        raise ValueError("WER is undefined for an empty reference")
    return Fraction(errors, words)
test_word_error_rate.py 66 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/word-error-rate/. The authors are listed in prov/8WQ3ZQ.jsonl.

import random
from fractions import Fraction
from functools import lru_cache

import pytest

from word_error_rate import align, corpus_wer, normalize, wer


def brute_edits(ref, hyp):
    """The least number of edits, by plain recursion over the first words."""

    @lru_cache(maxsize=None)
    def go(i, j):
        if i == len(ref):
            return len(hyp) - j
        if j == len(hyp):
            return len(ref) - i
        return min(go(i + 1, j + 1) + (ref[i] != hyp[j]), go(i + 1, j) + 1, go(i, j + 1) + 1)

    return go(0, 0)


def test_check_values():
    assert wer("the cat sat on the mat".split(), "the cat sit on mat".split()) == Fraction(1, 3)
    S, D, I, _ = align("the cat sat on the mat".split(), "the cat sit on mat".split())
    assert (S, D, I) == (1, 1, 0)
    assert wer("a b".split(), "x y z w".split()) == 2
    assert float(wer("the cat sat on the mat".split(), "the cat sit on mat".split())) == pytest.approx(0.333333, abs=1e-6)


def test_edge_cases():
    assert wer(["a", "b", "c"], []) == 1  # an empty hypothesis: every word deleted
    assert wer(["a", "b"], ["a", "b"]) == 0
    assert wer(["a"], ["a", "x", "y"]) == 2  # insertions only, above 1
    with pytest.raises(ValueError):
        wer([], ["a"])


def test_against_brute_force():
    rng = random.Random(1)
    vocab = ["a", "b", "c", "d"]
    for _ in range(300):
        ref = [rng.choice(vocab) for _ in range(rng.randint(1, 7))]
        hyp = [rng.choice(vocab) for _ in range(rng.randint(0, 7))]
        S, D, I, ops = align(ref, hyp)
        assert S + D + I == brute_edits(tuple(ref), tuple(hyp))
        # the alignment reads back the two strings
        assert [r for op, r, _ in ops if op != "I"] == ref
        assert [h for op, _, h in ops if op != "D"] == hyp
        assert D - I == len(ref) - len(hyp)


def test_corpus_wer_is_not_the_mean_of_sentence_wers():
    pairs = [(["a"], ["b"]), ("a b c d e f g h i".split(), "a b c d e f g h i".split())]
    assert corpus_wer(pairs) == Fraction(1, 10)
    assert (wer(*pairs[0]) + wer(*pairs[1])) / 2 == Fraction(1, 2)


def test_normalization_changes_the_score():
    ref, hyp = "The cat sat.", "the cat sat"
    assert wer(ref.split(), hyp.split()) == Fraction(2, 3)
    assert wer(normalize(ref), normalize(hyp)) == 0

References

  1. Robert A. Wagner and Michael J. Fischer, The string-to-string correction problem, Journal of the ACM 21(1), 1974, pages 168 to 173, the dynamic program for the least number of edit operations
  2. Xuedong Huang, Alex Acero and Hsiao-Wuen Hon, Spoken Language Processing, Prentice Hall PTR, 2001, Chapter 9 (acoustic modeling), the measurement of recognition errors
  3. Mark Gales and Steve Young, The application of hidden Markov models in speech recognition, Foundations and Trends in Signal Processing 1(3), 2008, pages 195 to 304, the word error rates of the systems that the survey compares

Where this leads

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

LadderLevelWhat the next level needs
Human proofH0 no proof
  • add a proof in proofs/ (06.5)
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
Code (python)I0 not checked yet
  • the tests did not run in this build
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW4 complete
  • a review of the text: no review record reviews/8WQ3ZQ/text.yaml