AI Wiki中文/EN

Evaluating speech systems: denominators, envelopes and listeners

语音系统评测

Explain WER ranking reversals, paired cluster resampling, envelope correlation and separate listening dimensions.

On this pageIntuitionMathematics & methodImplementationLimitationsExercisesResearch connections

How can the same two recognition outputs produce different winners?

Consider an invented two-sentence test set. A short sentence contains one word: system A gets it wrong and B gets it right. A long sentence contains nine words: A gets every word right and B makes three errors. Pool all reference words and A has 1/10 errors against B’s 3/10, so A wins. Average sentence error rates instead and A scores (1+0)/2 = 0.5 against B’s (0+1/3)/2 ≈ 0.167, so B wins. The recognition outputs did not change. Their weights in the aggregate did.

Speech-system evaluation begins by specifying the task. Recognition asks whether a transcript is correct. Enhancement also raises questions about noise, intelligibility and distortion; synthesis requires attention to content and listening quality. One error rate cannot answer all of them. Even when two reports both say WER or MOS, inspect their references, normalization, sampling and aggregation conventions.

This article performs four reproducible tasks: word edit distance; aggregation and paired resampling; correlation of one supplied envelope; and separate aggregation of invented ratings in three listening dimensions. These components examine evaluation logic. They are not complete STOI, DNSMOS or a human listening study. jiwer recognition metrics STOI paper DNSMOS rating dimensions

Review the input-output problem in automatic speech recognition and the resampling idea in Bootstrap. Here we examine how comparative conclusions are obtained, rather than training another recognizer.

WER weighting, paired speaker draws, envelope normalization and invented listening dimensions show what each score measures.
WER weighting, paired speaker draws, envelope normalization and invented listening dimensions show what each score measures.

A score needs an explicit protocol

Word error rate: the denominator counts reference words

Write reference tokens as r1,…,rnr_1,\ldots,r_n and hypothesis tokens as h1,…,hmh_1,\ldots,h_m. Substitution S, deletion D and insertion I each cost one; a correct hit H costs zero. Let C(i,j)C(i,j) be the minimum edit cost between the two prefixes:

C(i,j)=min⁡ ⁣{C(i−1,j−1)+1[ri≠hj], C(i−1,j)+1, C(i,j−1)+1}.C(i,j)=\min\!\left\{C(i-1,j-1)+\mathbf1[r_i\ne h_j],\ C(i-1,j)+1,\ C(i,j-1)+1\right\}.

Boundaries C(i,0)=iC(i,0)=i and C(0,j)=jC(0,j)=j represent deleting the reference or inserting the hypothesis. The program saves traceback directions to recover operation counts. Different alignments can tie. We break ties in diagonal, deletion, insertion order, so individual error labels need not match every tool.

WER⁡=S+D+In(n>0),H+S+D=n,H+S+I=m.\operatorname{WER}=\frac{S+D+I}{n}\quad(n>0),\qquad H+S+D=n,\qquad H+S+I=m.

For reference “yes” and hypothesis “no extra words,” one substitution and two insertions give WER = 3/1 = 3, or 300%. WER counts edits per reference word; it is not a probability that a word is wrong. The program splits on whitespace and preserves case and punctuation. “Hello, world” against “hello world” incurs one substitution and WER 0.5. If a task permits ignoring case, fix that normalization rule and apply it consistently to every system. Do not change the rule for one system after seeing its results.

jiwer computes WER using minimum edit distance, but version 4 has a different empty-reference convention: empty reference and hypothesis give zero, while a nonempty hypothesis against an empty reference gives the insertion count. Our example returns None when the reference word count is zero and reports insertions separately. Both conventions need explicit reporting; a library output is not the only possible mathematical definition. Pinned jiwer explanation Aggregation code

Pooled errors, sentence averages and sentence failures use different weights

Let sentence ii contain nin_i reference words and eie_i edits. Let MM be the sentence count and I+\mathcal I_+ the set with nonempty references:

WER⁡pooled=∑iei∑ini,WER⁡macro=1∣I+∣∑i∈I+eini,SER⁡=1M∑i1[ei>0].\operatorname{WER}_{\mathrm{pooled}}=\frac{\sum_i e_i}{\sum_i n_i},\qquad\operatorname{WER}_{\mathrm{macro}}=\frac1{|\mathcal I_+|}\sum_{i\in\mathcal I_+}\frac{e_i}{n_i},\qquad\operatorname{SER}=\frac1M\sum_i\mathbf1[e_i>0].

Pooled WER divides by all reference words and includes insertions on empty-reference sentences in its numerator. Macro WER averages only nonempty-reference sentences, explicitly excluding empty ones. SER counts the fraction of sentences with any edit error. In the opening example, both systems have SER 0.5; that score cannot distinguish their different error counts. Cross-sentence counts

Keep sentence, reference-word and error counts in the summary table. “Error rate fell by 20%” is still ambiguous: a change from 0.3 to 0.1 is twenty percentage points, or about a 66.7% relative reduction. Longer sentences are not inherently more or less important. Choose weights to fit the application’s objective.

Paired resampling: keep a speaker’s sentences together

When comparing A and B, preserve each reference and both outputs as a unit. If a speaker contributes several recordings, resample whole speaker clusters with replacement to retain shared within-cluster variation. Suppose there are SS clusters, with reference counts nsn_s and error counts as,bsa_s,b_s. Each replicate draws SS cluster identifiers:

Jt∼iidUniform⁡{1,…,S},Δ∗=∑t=1S(aJt−bJt)∑t=1SnJt.J_t\overset{\mathrm{iid}}\sim\operatorname{Uniform}\{1,\ldots,S\},\qquad\Delta^*=\frac{\sum_{t=1}^S(a_{J_t}-b_{J_t})}{\sum_{t=1}^S n_{J_t}}.

Recompute numerator and denominator in every replicate. Do not replace this ratio with an unweighted average of cluster WER differences. We use two to four clusters and enumerate all SSS^S equally likely draw sequences. Assign the opening short and long sentences to two invented speakers. The four A−B differences are 1, −0.2, −0.2 and −1/3. The observed difference is −0.2, but linearly interpolated 2.5th and 97.5th percentiles give approximately [−0.323333, 0.91], which includes zero.

Enumeration removes finite Monte Carlo sampling noise; it does not add speakers. With only two clusters, the interval has no assured population coverage, and resampling cannot repair a biased test set. Every cluster must contain reference words in this example to avoid zero-denominator replicates. If real data violates this condition, separate the empty-reference task or explicitly redefine the analysis protocol. Resampling foundations

An intelligibility envelope: double the gain, retain correlation one

The 2010 STOI paper forms band envelopes from a time-frequency representation, normalizes and clips them within short windows, computes correlation, then averages over windows and bands. Our example takes just one supplied nonnegative band envelope x,yx,y for one window. It does not implement resampling, STFT, band aggregation, silence processing or full score aggregation. Paper equations 1–5

First align energy scales, then limit excessive envelope deviations. Choose a negative clipping parameter β\beta:

α=∥x∥2∥y∥2,un=min⁡ ⁣(αyn,(1+10−β/20)xn),β<0.\alpha=\frac{\|x\|_2}{\|y\|_2},\qquad u_n=\min\!\left(\alpha y_n,(1+10^{-\beta/20})x_n\right),\qquad\beta<0.

The original expression also has a lower bound (1−10−β/20)xn(1-10^{-\beta/20})x_n. With β<0\beta<0 and nonnegative inputs, that bound is nonpositive, so the lower clipping operation can be omitted here. The simplification is not automatically valid with a different parameter range or negative envelopes.

d=(x−xˉ1)⊤(u−uˉ1)∥x−xˉ1∥2 ∥u−uˉ1∥2.d=\frac{(x-\bar x\mathbf1)^\top(u-\bar u\mathbf1)}{\|x-\bar x\mathbf1\|_2\,\|u-\bar u\mathbf1\|_2}.

This is mean-centered correlation, not samplewise waveform MSE. For x=[1,2,3,4]x=[1,2,3,4], comparison with itself gives one, comparison with 2x2x still gives one, and comparison with the reversed envelope [4,3,2,1][4,3,2,1] gives −1. Normalization removes overall gain, so this component cannot establish that absolute loudness is correct.

Zero energy makes the scale ratio degenerate; a constant envelope makes the correlation denominator degenerate. The program returns None with a reason rather than forcing silence to score zero or one. The original authors investigated several windows and clipping settings and used N = 30, β = −15. Our N = 4 example is for hand calculation; its score of one must not be reported as a complete STOI score. Parameter and footnote conditions

Human ratings and predicted scores: identify their origin before comparing decimals

The DNSMOS P.835 paper distinguishes speech signal SIG, background noise BAK and overall quality OVRL, using human labels to train a predictor. A prediction depends on training labels and the input distribution. Removing the word “predicted” from a table does not turn it into a human rating. Dimensions and labels

Let ui,j,ku_{i,j,k} be listener ii‘s rating of clip jj in dimension kk. Let LL count listeners and MM count clips; this MM denotes clips, not the sentence count used earlier for WER. The following arithmetic mean first fixes these listeners and clips:

uˉk=1LM∑i=1L∑j=1Mui,j,k,δˉk=1L∑i=1L[1M∑j=1M(ui,j,kA−ui,j,kB)].\bar u_k=\frac1{LM}\sum_{i=1}^L\sum_{j=1}^M u_{i,j,k},\qquad\bar\delta_k=\frac1L\sum_{i=1}^L\left[\frac1M\sum_{j=1}^M(u^{A}_{i,j,k}-u^{B}_{i,j,k})\right].

All three listeners, two clips and scores in the program are invented. Mean A−B differences are −2/3 for SIG, +1 for BAK and −2/3 for OVRL. A quieter background does not ensure better speech or overall quality. Report the three dimensions separately instead of averaging them again into an invented “total MOS.”

For paired ratings, first average each listener’s A−B differences over the fixed clips, then resample listeners with replacement. Three listeners produce 27 enumerated replicates. This illustrates listener variation for that clip set; it does not cover uncertainty over new clips and is not a real listening study. We did not obtain the full ITU P.835 text, so this article does not claim to provide its complete normative protocol. The source here is the DNSMOS authors’ description

Output the counts and degenerate cases together

The complete program uses Python 3.12 and NumPy 1.26.4. No audio, recognizer or paid service is needed; transcripts, envelopes and ratings are explicit in demo. Outputs retain H/S/D/I, sentence-level records, denominators, empty-reference insertions and resampled differences, instead of leaving an untraceable decimal.

"""Original bounded speech-evaluation components, no speech model or listening.

Exact-token unit-cost WER with explicit empty-reference policy; paired cluster
bootstrap enumeration; supplied-band STOI-2010-style envelope component; and
aggregation of invented listener ratings. This is not official STOI/DNSMOS.
"""
import itertools
import json
import numpy as np


def tokens(value):
    if type(value) is not str or len(value)>4096:raise ValueError('Use bounded transcript text')
    words=value.split()
    if len(words)>128 or any(len(w)>64 for w in words):raise ValueError('Too many or overlong tokens')
    return words


def align(reference,hypothesis):
    ref=tokens(reference);hyp=tokens(hypothesis);n,m=len(ref),len(hyp)
    cost=np.zeros((n+1,m+1),int);cost[:,0]=np.arange(n+1);cost[0]=np.arange(m+1);back={}
    for i in range(1,n+1):
        for j in range(1,m+1):
            same=ref[i-1]==hyp[j-1]
            value,_,op=min((cost[i-1,j-1]+(not same),0,'H' if same else 'S'),(cost[i-1,j]+1,1,'D'),(cost[i,j-1]+1,2,'I'))
            cost[i,j]=value;back[i,j]=op
    i,j=n,m;operations=[];counts={k:0 for k in 'HSDI'}
    while i or j:
        op='I' if i==0 else 'D' if j==0 else back[i,j];counts[op]+=1;operations.append(op)
        if op in ('H','S','D'):i-=1
        if op in ('H','S','I'):j-=1
    edits=int(cost[n,m])
    return dict(reference_words=n,hypothesis_words=m,edits=edits,wer=edits/n if n else None,empty_reference=(n==0),sentence_error=(edits>0),counts=counts,operations=operations[::-1])


def evaluate(records):
    if not isinstance(records,list) or not 1<=len(records)<=16:raise ValueError('Use 1 to 16 paired records')
    ids=[];rows=[]
    for row in records:
        if not isinstance(row,dict) or set(row)!={'id','speaker','reference','a','b'} or any(type(row[k]) is not str or not 1<=len(row[k])<=40 for k in ['id','speaker']):raise ValueError('Invalid paired record')
        ids.append(row['id']);a=align(row['reference'],row['a']);b=align(row['reference'],row['b']);rows.append(dict(id=row['id'],speaker=row['speaker'],a=a,b=b))
    if len(ids)!=len(set(ids)):raise ValueError('Record identifiers must be unique')
    total=sum(row['a']['reference_words'] for row in rows);summary={}
    for key in ['a','b']:
        edits=sum(row[key]['edits'] for row in rows);defined=[row[key]['wer'] for row in rows if row[key]['wer'] is not None]
        summary[key]=dict(edits=edits,pooled_wer=edits/total if total else None,macro_wer=float(np.mean(defined)) if defined else None,sentence_error_rate=float(np.mean([row[key]['sentence_error'] for row in rows])),empty_reference_insertions=sum(row[key]['counts']['I'] for row in rows if row[key]['empty_reference']))
    return dict(reference_words=total,summary=summary,rows=rows)


def paired_bootstrap(records):
    evaluation=evaluate(records);rows=evaluation['rows'];names=sorted({row['speaker'] for row in rows})
    if not 2<=len(names)<=4:raise ValueError('Exact bootstrap uses 2 to 4 speaker clusters')
    clusters=[]
    for name in names:
        group=[row for row in rows if row['speaker']==name];n=sum(row['a']['reference_words'] for row in group)
        if not n:raise ValueError('Every resampling cluster must contain reference words')
        clusters.append((n,sum(row['a']['edits'] for row in group),sum(row['b']['edits'] for row in group)))
    differences=[]
    for indices in itertools.product(range(len(names)),repeat=len(names)):
        n,a,b=np.sum([clusters[i] for i in indices],axis=0);differences.append(float((a-b)/n))
    return dict(cluster_names=names,replicates=len(differences),differences=differences,observed_delta=evaluation['summary']['a']['pooled_wer']-evaluation['summary']['b']['pooled_wer'],percentile_95=np.quantile(differences,[.025,.975],method='linear').tolist(),method='Paired speaker resampling with replacement; finite bootstrap approximation, not a coverage guarantee')


def envelope_component(reference,processed,beta=-15):
    x=np.asarray(reference);y=np.asarray(processed)
    if x.dtype.kind not in 'fiu' or y.dtype.kind not in 'fiu' or x.ndim!=1 or not 2<=len(x)<=64 or y.shape!=x.shape or not np.isfinite(x).all() or not np.isfinite(y).all() or np.any((x<0)|(x>8)) or np.any((y<0)|(y>8)) or type(beta) not in (int,float) or not -30<=beta<=-1:raise ValueError('Use bounded nonnegative supplied envelopes and negative beta')
    x=x.astype(float);y=y.astype(float);nx=np.linalg.norm(x);ny=np.linalg.norm(y)
    if min(nx,ny)<=1e-12:return dict(status='degenerate-energy',score=None,alpha=None,clipped=None)
    alpha=nx/ny;clipped=np.minimum(alpha*y,(1+10**(-beta/20))*x);xc=x-x.mean();yc=clipped-clipped.mean();den=np.linalg.norm(xc)*np.linalg.norm(yc)
    if den<=1e-12:return dict(status='constant-envelope',score=None,alpha=float(alpha),clipped=clipped.tolist())
    return dict(status='defined',score=float(np.clip(xc@yc/den,-1,1)),alpha=float(alpha),clipped=clipped.tolist())


def ratings_summary(a,b):
    x=np.asarray(a);y=np.asarray(b)
    if x.dtype.kind not in 'fiu' or y.dtype.kind not in 'fiu' or x.ndim!=3 or not 2<=x.shape[0]<=4 or not 1<=x.shape[1]<=8 or x.shape[2]!=3 or y.shape!=x.shape or not np.isfinite(x).all() or not np.isfinite(y).all() or np.any((x<1)|(x>5)) or np.any((y<1)|(y>5)):raise ValueError('Use paired listener x clip x three-dimension ratings in [1,5]')
    x=x.astype(float);y=y.astype(float);delta=(x-y).mean(axis=1);replicates=[]
    for indices in itertools.product(range(len(x)),repeat=len(x)):replicates.append(delta[list(indices)].mean(axis=0))
    return dict(dimensions=['SIG','BAK','OVRL'],a=x.mean(axis=(0,1)).tolist(),b=y.mean(axis=(0,1)).tolist(),paired_mean_delta=delta.mean(axis=0).tolist(),listener_bootstrap_95=np.quantile(replicates,[.025,.975],axis=0,method='linear').T.tolist(),replicates=len(replicates),scope='Invented paired ratings; listener resampling for this fixed clip set, not a real listening study or predicted MOS')


def demo():
    sentence='one two three four five six seven eight nine'
    records=[dict(id='short',speaker='S1',reference='yes',a='no',b='yes'),dict(id='long',speaker='S2',reference=sentence,a=sentence,b='X Y Z four five six seven eight nine')]
    empty=align('','invented extra words');a=[[[3,5,3],[4,4,4]],[[3,4,3],[3,5,3]],[[4,5,4],[4,4,4]]];b=[[[4,3,4],[4,4,4]],[[4,3,4],[4,4,4]],[[5,4,5],[4,3,4]]]
    return dict(protocol='Exact whitespace tokens, case-sensitive, punctuation retained; unit edit costs, diagonal/deletion/insertion tie order',corpus=evaluate(records),bootstrap=paired_bootstrap(records),empty_reference=empty,
        normalization=align('Hello, world','hello world'),over_100_percent=align('yes','no extra words'),
        envelope_cases={key:envelope_component([1,2,3,4],value) for key,value in [('same',[1,2,3,4]),('gain',[2,4,6,8]),('reversed',[4,3,2,1]),('silent',[0,0,0,0]),('constant',[2,2,2,2])]},ratings=ratings_summary(a,b))


if __name__=='__main__':print(json.dumps(demo(),indent=2,allow_nan=False))

Check the default results directly:

ComparisonSystem ASystem B or referenceInterpretation
Pooled WER0.10.3All ten reference words
Macro WER0.51/6Two nonempty-reference sentences weighted equally
SER0.50.5Each system fails one of two sentences
Envelope xx against xx and 2x2x11Does not measure absolute gain
Invented SIG/BAK/OVRL differences−2/3, +1, −2/3A−BDimensions can move in different directions

Edit distance costs O(nm)O(nm) time and space; references and hypotheses are each capped at 128 tokens. Exact speaker-bootstrap enumeration costs approximately O(SSS)O(S^S S), suitable only for our two-to-four-cluster teaching scale. Larger analyses should specify random replicate counts and seeds instead of copying exponential enumeration. One envelope calculation costs O(N)O(N) with at most 64 entries; ratings are limited to four listeners and eight clips.

The program compares 225 pairs of short strings against an independent recursive edit-distance calculation. It also checks that H+S+D equals reference length and H+S+I equals hypothesis length. Those checks validate arithmetic, not the tokenization or weighting policy appropriate to a real application.

Do not keep only the easiest sounds to evaluate

Engineering evaluation needs a baseline that requires no newly trained model. Examples include a fixed existing recognizer with a fixed normalization protocol, or an enhancement bypass that returns the noisy input unchanged. This article implements scoring components but runs neither baseline, so it claims no improvement over them. Actual comparisons should examine errors by speaker, device, noise and language. Grouping and privacy decisions must reflect the real data conditions.

Test examples may share speakers, sessions or even one original recording. Simple sentence-level bootstrap can break those dependencies. Conversely, choosing speakers as clusters does not automatically control every device or session factor. Match the resampling unit to the intended population rather than choosing whichever method narrows the interval.

Speed evaluation should distinguish audio duration, time to complete a transcript and time to the first usable result, recording hardware, batch size, warmup and input length. Equally accurate systems can have different operational costs. No model latency was measured here; see model evaluation for further engineering checks.

Predict which score will change

  1. Calculate the ranking reversal. For the opening one-word/nine-word test set, calculate each system’s pooled WER, macro WER and SER. Explain the reversal.

Answer: A has pooled WER 1/10 = 0.1 and B has 3/10 = 0.3. Their macro scores are (1+0)/2 = 0.5 and (0+3/9)/2 = 1/6. Both have SER 1/2. Pooled WER weights by reference words; macro WER weights sentences equally. Different weights for short and long sentences reverse the ranking.

  1. Handle empty references and insertions. The reference is empty and the hypothesis is “invented extra words.” What does our example return, and why is WER not necessarily zero?

Answer: It returns three insertions, WER None and a sentence error. The usual ratio has zero reference words in its denominator. jiwer v4 instead defines WER here as the insertion count, three. State the convention. Silently assigning zero would hide hallucinated transcription when there is no speech.

  1. Identify a score’s blind spot. Given x=[1,2,3,4]x=[1,2,3,4] and y=2xy=2x, calculate α\alpha and our envelope correlation. Does this establish correct loudness?

Answer: α=1/2\alpha=1/2, so normalization recovers xx, clipping leaves it unchanged and centered correlation is one. This does not establish correct loudness: normalization removed the overall gain. It is also not a complete STOI run.

  1. Interpret an interval containing zero. The two-speaker paired differences are 1, −0.2, −0.2 and −1/3, with a 95% percentile interval of roughly [−0.323333, 0.91]. Does this establish equal performance?

Answer: No. Including zero means this small resampling comparison has not excluded zero difference; it is not proof of equivalence. Two speakers also cannot assure interval coverage. Collect more independent clusters representative of the intended population, and define meaningful differences or equivalence bounds in advance.

Read metric papers and inspect tool boundary policies

Taal and colleagues’ 2010 conference paper supports the envelope normalization, clipping and correlation conditions used here. It is distinct from their differently titled 2011 journal paper. DNSMOS P.835 v1 supports the distinction among rating dimensions and between predicted scores and human labels. We reproduce neither its model nor results, and do not treat the unavailable ITU standard as a read source. STOI paper DNSMOS paper

jiwer is pinned to 2227002889f20f3fb19d523eeb322732cb67b431. Its README and scoped process.py sections show edit distance, count aggregation and empty-reference policies. The opening of its Apache 2 license was read, not fully audited; no upstream code was copied or executed. Our algorithm has its own tie order and None policy. Check those differences before comparing outputs. Project explanation Aggregation implementation

Make a prediction, then check

What explains opposite pooled and macro WER rankings on the same outputs?

Choose one answer

Learning objectives

  • Specify edit costs, normalization and empty-reference policy before scoring.
  • Compute pooled and macro WER and explain a ranking reversal.
  • Keep paired systems and speaker clusters intact during resampling.
  • Distinguish envelope components, predicted scores and actual human ratings.

Prerequisites & connections

Explore related knowledge →

References

  1. jiwer metric and empty-reference conventions at 2227002
    jiwer contributors
  2. jiwer edit aggregation at 2227002
    jiwer contributors
  3. A Short-Time Objective Intelligibility Measure for Time-Frequency Weighted Noisy Speech
    Cees H. Taal; Richard C. Hendriks; Richard Heusdens; Jesper Jensen · 2010
  4. DNSMOS P.835: A Non-Intrusive Perceptual Objective Speech Quality Metric to Evaluate Noise Suppressors (v1)
    Chandan K A Reddy; Vishak Gopal; Ross Cutler · 2021

Version1 · Editorial status: Recorded technical checks completed

View technical check record (AI)

Codex · 2026-09-13 · Single AI author checked jiwer fixed edit/empty-reference policies, STOI2010 envelope conditions and DNSMOSv1 label/prediction distinctions. Seven paired equations, four explained exercises, independent edit oracle, aggregation reversal, paired cluster enumeration and invented rating dimensions. ITU normative text unavailable; no complete STOI, DNSMOS or human study.

  • Verified225 short-string pairs against independent recursive distance, H/S/D/I conservation, None empty-reference policy, pooled/macro rank reversal, four paired speaker draws, envelope degeneracy and27 invented-listener resamples.
  • Four computed SVGs bind exact bilingual MDX. The two-topic group passed10 numeric/encoding checks and12 isolated language/width cases with four fallback fonts; four representative final screenshots inspected by the AI author. Mobile heading clipping and bar spacing corrected with originals preserved. Literal-prose AST checked before freezing. Full article browser acceptance is separate; no human peer review.

Source locations checked:

Related topics

No matches. Try a synonym or acronym.

0 results shown

Wrap the whole query in double quotes for a phrase match.