Word error rate
Problem
Split both strings on whitespace. Return (S + D + I)/N, where S, D and I come from the minimum word-level edit distance (unit cost substitution, deletion, insertion) and N is the number of reference words. Raise ValueError if the reference has no words.
Signature
def word_error_rate(reference: str, hypothesis: str) -> float: ...Examples
The visible tests, as an interactive Python session would show them: each call and the value it should give.
>>> close(word_error_rate('the cat sat', 'the cat sat'), 0.0)
True
>>> close(word_error_rate('the cat sat', 'the bat sat'), 0.333333)
TrueHints
Run a word-level edit-distance DP (unit cost) between reference and hypothesis.
WER = (S + D + I) / N where N is the number of reference words.
Raise ValueError when the reference has no words; keep an O(M) rolling row.
Reference solution
def word_error_rate(reference, hypothesis):
r = reference.split(); h = hypothesis.split()
if not r:
raise ValueError("empty reference")
prev = list(range(len(h) + 1))
for i in range(1, len(r) + 1):
cur = [i] + [0] * len(h)
for j in range(1, len(h) + 1):
cur[j] = min(prev[j] + 1, cur[j - 1] + 1, prev[j - 1] + (r[i - 1] != h[j - 1]))
prev = cur
return prev[-1] / len(r)What a strong solution covers
- O(N·M) DP with an O(M) rolling row.
- Correct initial row/column.
- Notes that WER can exceed 1.
- Discusses text normalisation (case, punctuation) and alignment back-tracing for error analysis.
Common mistakes
- dividing by hypothesis length
- character-level instead of word-level distance.