AI Wiki中文/EN

Speech recognition: from audio to accountable transcripts

自动语音识别

Trace the ASR pipeline and compute explicit word/character errors, empty-reference behavior and aggregation reversals.

On this pageIntuitionMathematics & methodImplementationLimitationsExercisesResearch connections

Do fewer word errors make a system more useful?

The reference says “do not enter”; the system writes “do enter.” It deletes only one of three words but changes a prohibition into permission. Automatic speech recognition (ASR) converts sound into text. Evaluating it requires reproducible error measures and an understanding of which errors change the outcome of using that text.

Consider a hypothetical meeting-transcription project that has not been deployed. Input includes audio with timing, channels and recording context; output represents what was said. Punctuation restoration, speaker diarization, translation and summarization are different tasks. Fluent text does not establish success at all of them. Whisper encodes several tasks as decoder prefixes, but transcription and translation still have different targets. Multitask transcription format

We first separate the system’s stages, then implement an inspectable scorer. Its inputs are existing reference and hypothesis transcripts; it does not hear audio or implement a speech model. It reveals conditions often missing from score comparisons: word versus character units, normalization, alignment, sentence weighting and empty references.

The same two systems change rank under corpus pooling and sentence averaging. Empty-reference insertions and lost negation show why one score needs explicit conditions.
The same two systems change rank under corpus pooling and sentence averaging. Empty-reference insertions and lost negation show why one score needs explicit conditions.

Which layer makes which decision?

Let X=(x1,…,xT)X=(x_1,\ldots,x_T) be acoustic features and YY a candidate text or token sequence. Recognition commonly seeks the most probable conditional output:

Y^=arg⁡max⁡YP(Y∣X).\hat Y=\arg\max_Y P(Y\mid X).

This is not framewise argmax. The same text can have many temporal alignments, and a decoder must compare different prefixes and lengths. Traditional systems can combine an acoustic model, pronunciation lexicon and language model, with Bayes’ rule clarifying their roles:

Y^=arg⁡max⁡YP(X∣Y)P(Y).\hat Y=\arg\max_Y P(X\mid Y)P(Y).

The common denominator P(X)P(X) is removed for fixed input. For continuous XX, interpret P(X∣Y)P(X\mid Y) as a density. Practical systems may additionally weight acoustic, language or length terms. Such scoring choices do not make arbitrary weighted scores exact posterior probabilities. CTC, RNN-T and encoder–decoder systems have their own conditional assumptions and search procedures; removing a stage does not automatically improve correctness.

Engineering begins with the audio contract: sample rate, channels, duration, encoding, silence and clipping. A front end may use MFCCs, log-Mel or learned waveform representations. The model supplies a distribution; decoding produces text; explicit rules may then handle case, numbers and punctuation. Split training, validation and test data by speakers, recording sessions or collection sources where appropriate, avoiding leakage from fragments of the same recording. Real projects also need coverage of noise, accents, devices and recording lengths.

Evaluation needs trustworthy references. References can omit words, contain uncertain speech or follow different writing conventions. NIST’s sclite documentation supports alternative references and optional NULL words to handle some ambiguities. Our small scorer accepts one definite reference and does not implement those extensions. References and alignment rules

Suppose the reference has NN units and the hypothesis MM. The dynamic-programming entry D(i,j)D(i,j) is minimum cost between prefixes. Costs cS,cD,cIc_S,c_D,c_I denote substitution, deletion and insertion:

D(i,j)=min⁡{D(i−1,j−1)+cS1[ri≠hj],D(i−1,j)+cD,D(i,j−1)+cI,D(i,0)=icD,D(0,j)=jcI.D(i,j)=\min\begin{cases}D(i-1,j-1)+c_S\mathbf1[r_i\ne h_j],\\D(i-1,j)+c_D,\\D(i,j-1)+c_I,\end{cases}\quad D(i,0)=ic_D,\quad D(0,j)=jc_I.

Traceback counts correct units CC, substitutions SS, deletions DD and insertions II; arguments distinguish the table D(i,j)D(i,j) from deletion count DD. Our default assigns unit cost to each error. The inspected sclite manual instead assigns correct/insertion/deletion/substitution costs 0/3/3/4. Weighted-optimal alignment need not produce the same error breakdown. We therefore report configuration, optimized cost and unweighted error count separately. sclite weights

WER=S+D+IN,N>0.\mathrm{WER}=\frac{S+D+I}{N},\qquad N>0.

Using character units gives character error rate (CER), but “character” needs a definition. Our word mode splits whitespace; character mode uses non-whitespace Unicode code points after NFC normalization, not grapheme clusters or automatic Chinese word segmentation. Reference “中文” and hypothesis “中 文” produce two edits with denominator one in word mode and zero errors in character mode. Different scoring units are not directly comparable.

WER is not bounded by one. Reference “go” and output “go now please” give two insertions and WER=2. An empty reference has zero denominator, making per-utterance WER undefined; hallucinated insertions should still be reported instead of treating the utterance as perfect. Corpus pooling and sentence averaging also differ:

WERmicro=∑iEi∑iNi,WERmacro=1∣J∣∑i∈JEiNi,Ei=Si+Di+Ii,J={i:Ni>0}.\mathrm{WER}_{\mathrm{micro}}=\frac{\sum_i E_i}{\sum_iN_i},\qquad \mathrm{WER}_{\mathrm{macro}}=\frac1{|J|}\sum_{i\in J}\frac{E_i}{N_i},\quad E_i=S_i+D_i+I_i,\quad J=\{i:N_i>0\}.

Two invented samples have lengths 10 and 1. System A makes one error only in the short sample: micro 1/11 and macro 0.5. B makes two errors in the long sample and none in the short: micro 2/11 and macro 0.1. Valid aggregation choices reverse the ranking. When every reference is nonempty, the first weights sentence error rates by reference-unit count; the second gives sentences equal weight. Empty-reference insertions remain in the pooled numerator, so that weighted-average interpretation needs this qualification. Report how many sentences actually enter the macro average.

SER=#{i:Ei>0}K,RTF=processing secondsaudio seconds.\mathrm{SER}=\frac{\#\{i:E_i>0\}}{K},\qquad \mathrm{RTF}=\frac{\text{processing seconds}}{\text{audio seconds}}.

Sentence error rate (SER) is the proportion of KK utterances with any edit error. Real-time factor (RTF) measures processing speed. A value below 1 means processing took less time than the audio’s duration under that measurement; it does not guarantee low first-output latency or streaming operation. Specify hardware, precision, batch size and inclusion of loading or network time. Our example calculates text metrics and does not measure RTF.

Keep the error path, not just a score

The complete standard-library Python scorer supports up to 16 utterances, 128 units per utterance and 100 characters per token. normalize=True applies NFC, casefolding and removal of only the explicitly listed English/Chinese punctuation marks, retaining apostrophes. It is not Whisper’s full multilingual normalizer. The Whisper paper explains how normalization changes WER and cautions against assuming rules adjusted to evaluation data are unconditionally fair. WER and normalization

"""Finite ASR transcript scoring with explicit tokenization and alignment costs.

Synthetic outputs only: this evaluator neither hears audio nor identifies words.
"""
import json
import unicodedata


def tokens(text,unit='word',normalize=False):
    if not isinstance(text,str) or len(text)>2000 or unit not in ('word','character') or type(normalize) is not bool:raise ValueError('Use bounded text, a named unit and a boolean normalization flag')
    s=unicodedata.normalize('NFC',text)
    if normalize:s=''.join(c for c in s.casefold() if c not in '.,!?,。!?')
    result=s.split() if unit=='word' else [c for c in s if not c.isspace()]
    if len(result)>128:raise ValueError('At most 128 scoring units')
    return result


def align(reference,hypothesis,costs=(1,1,1)):
    if not isinstance(reference,(list,tuple)) or not isinstance(hypothesis,(list,tuple)) or max(len(reference),len(hypothesis))>128 or any(not isinstance(x,str) or not x or len(x)>100 for x in list(reference)+list(hypothesis)):raise ValueError('Use bounded nonempty string tokens')
    if len(costs)!=3 or any(type(x) is not int or not 1<=x<=10 for x in costs):raise ValueError('Positive integer substitution/deletion/insertion costs required')
    sub,delete,insert=costs;n=len(reference);m=len(hypothesis);d=[[0]*(m+1) for _ in range(n+1)];back={}
    for i in range(1,n+1):d[i][0]=i*delete;back[i,0]='D'
    for j in range(1,m+1):d[0][j]=j*insert;back[0,j]='I'
    for i in range(1,n+1):
        for j in range(1,m+1):
            same=reference[i-1]==hypothesis[j-1]
            candidates=[(d[i-1][j-1]+(0 if same else sub),0,'C' if same else 'S'),(d[i-1][j]+delete,1,'D'),(d[i][j-1]+insert,2,'I')]
            value,_,op=min(candidates);d[i][j]=value;back[i,j]=op
    i,j=n,m;path=[];counts={k:0 for k in 'CSDI'}
    while i or j:
        op=back[i,j];counts[op]+=1;path.append(dict(operation=op,reference=reference[i-1] if op!='I' else None,hypothesis=hypothesis[j-1] if op!='D' else None))
        i-=op!='I';j-=op!='D'
    errors=counts['S']+counts['D']+counts['I']
    return dict(reference_length=n,hypothesis_length=m,cost=d[n][m],costs=list(costs),counts=counts,errors=errors,error_rate=errors/n if n else None,path=path[::-1],tie_policy='diagonal, deletion, insertion')


def evaluate(references,hypotheses,unit='word',normalize=False,costs=(1,1,1)):
    if not isinstance(references,(list,tuple)) or not isinstance(hypotheses,(list,tuple)) or not 1<=len(references)<=16 or len(references)!=len(hypotheses):raise ValueError('Use 1–16 paired utterances')
    rows=[align(tokens(r,unit,normalize),tokens(h,unit,normalize),costs) for r,h in zip(references,hypotheses)]
    n=sum(r['reference_length'] for r in rows);errors=sum(r['errors'] for r in rows);defined=[r['error_rate'] for r in rows if r['error_rate'] is not None]
    return dict(unit=unit,normalize=normalize,utterances=rows,errors=errors,reference_units=n,micro_error_rate=errors/n if n else None,macro_error_rate=sum(defined)/len(defined) if defined else None,macro_defined=len(defined),sentence_error_rate=sum(r['errors']>0 for r in rows)/len(rows),empty_reference_insertions=sum(r['errors'] for r in rows if r['reference_length']==0))


def demo():
    refs=['one two three four five six seven eight nine ten','yes'];a=[refs[0],'no'];b=['one two three four five six seven eight X Y','yes']
    return dict(references=refs,A=evaluate(refs,a),B=evaluate(refs,b),above_one=evaluate(['go'],['go now please']),
                empty=evaluate(['','yes'],['invented words','yes']),all_empty=evaluate([''],['invented']),
                normalization=dict(raw=evaluate(['HELLO, world!'],['hello world']),normalized=evaluate(['HELLO, world!'],['hello world'],normalize=True)),
                units=dict(word=evaluate(['中文'],['中 文']),character=evaluate(['中文'],['中 文'],unit='character')),
                cost_policy=dict(unit=align(['a','b'],['b','a']),sclite_weights=align(['a','b'],['b','a'],(4,3,3))),
                semantic_counterexample=evaluate(['do not enter'],['do enter']))


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

Each alignment table and traceback use O((N+1)(M+1))O((N+1)(M+1)) time and storage, including empty inputs. Accounting for string-comparison cost multiplies the time bound by maximum token length; tokenization is linear in characters. Ties consistently prefer diagonal, deletion, then insertion, making error paths reproducible. There is no timestamp alignment, alternative-reference handling or minimum-memory optimization.

demo preserves ranking reversal, WER above 1, empty references, word/character differences and lost negation. An empty reference with two inserted words plus a correct “yes” gives corpus micro 2 but nonempty-only macro 0, exposing what omission of empty references hides. Costs also change the alignment of “a b” versus “b a”: unit costs favor two substitutions, while the sclite-weight configuration selects one deletion and one insertion.

For the hypothetical meeting project, first compare human transcription as a time-and-cost baseline. If only a few dozen fixed commands are needed, test whether manual options or restricted command input suffice. An actual open-vocabulary transcription need calls for a fixed model and decoder baseline on real audio, followed by error analysis across speakers and conditions. This scorer cannot substitute for that experiment.

Write comparability conditions into the result

The same WER can arise from losing negation, misspelling a name or inserting a filler, with different consequences. Inspect alignment paths and predefined task-specific slices such as entities, negation and numbers. Those additional measures should not be chosen afterward solely because they favor one system. Reference checking and audio-quality inspection remain necessary.

A stronger language prior may improve fluency while making plausible guesses on unclear audio. Long-form chunk boundaries, preceding-text conditioning and repetitions can also escape one short-utterance score. The Whisper paper uses several heuristics to mitigate long-form problems, and its model card acknowledges that unspoken text can remain. Text scoring here does not establish that any system has solved those problems. System and evaluation boundaries Model card

State the conditions before judging a score

  1. Understanding. Are subtitles, speaker diarization, translation and summarization all the same as ASR?

    Answer: No. ASR’s core is transcription of spoken content. Other tasks add objectives and error types that require separate definitions and evaluation; transcript WER alone is insufficient.

  2. Calculation. For utterance lengths 10 and 1, A has errors[0, 1] and B[2, 0]. Which is better?

    Answer: Micro favors A’s1/11 over B’s2/11; macro favors B’s0.1 over A’s0.5. “Better” requires aggregation and application weights, not just a winner’s name.

  3. Boundary. Should an empty reference with two output words receive WER=0? What if reference “go” acquires two extra words?

    Answer: Empty-reference per-utterance WER is undefined; report two insertions separately. The nonempty “go” case has WER=2, showing there is no upper bound of one.

  4. Transfer. Can systems reporting WER and RTF under different case, punctuation, tokenization and hardware settings be ranked directly?

    Answer: No. Align data, scoring units, normalization and decoding protocols, then state hardware, batch size and timing scope. Inspect critical semantic errors too; one mean cannot replace a deployment judgment.

A tool manual and a model paper answer different parts

The pinned NIST SCTK sclite manual checks alignment weights and reference extensions; this program implements only its stated small subset of concerns. Task-format, evaluation and long-form sections of the Whisper ICML 2023 paper explain system conditions without presenting author-reported benchmarks as our replication. Inputs are synthetic text. There are no measured audio-recognition results, human-transcription costs or hardware-speed results.

Make a prediction, then check

Why can two valid WER summaries rank the same systems differently?

Choose one answer

Learning objectives

  • Separate transcription from adjacent speech tasks.
  • Specify audio, data-split and decoding contracts.
  • Compute edit counts and micro/macro errors.
  • Recognize empty references and consequential semantic errors.

Prerequisites & connections

Explore related knowledge →

References

  1. NIST SCTK: sclite manual at commit9688a268
    NIST SCTK contributors
  2. Robust Speech Recognition via Large-Scale Weak Supervision
    Alec Radford, Jong Wook Kim, Tao Xu, Greg Brockman, Christine McLeavey, Ilya Sutskever · 2023
  3. Whisper model card at commit86098128
    OpenAI Whisper contributors

Version1 · Editorial status: Recorded technical checks completed

View technical check record (AI)

Codex · 2026-09-13 · Single AI author checked the ASR system/scoring distinction, audio and split contracts, non-AI baselines, unit versus pinned NIST SCTK edit costs, Unicode scoring units, empty references, micro/macro ranking and negation consequences against scoped SCTK documentation and Whisper paper/card sections. Six paired equations, four explained exercises and an original bounded text scorer; no measured speech recognition, human cost or RTF result.

  • Checked micro1/11 versus2/11 and macro0.5 versus0.1, WER above1, empty-reference insertions, character/word differences, alternative edit costs and lost negation.
  • Four computed SVGs bind exact bilingual MDX. The five-topic group passed eleven numeric/encoding checks and 30 isolated language/width cases with four fallback fonts; ten actual screenshots inspected by the AI author. Literal-prose AST checked before freezing. Full article browser acceptance is separate; no human peer review.
  • After rendered review, inserted missing spaces before English reference citations. Verified an exact whitespace-only transformation, unchanged formulas/program and preserved frozen article/test payloads; see editorial/corrections/011h-citation-spacing.

Source locations checked:

  • NIST SCTK: sclite manual at commit9688a268 · Read dynamic-programming alignment weights0/3/3/4, alternative references and NULL discussion; fixed snapshot2023-11-27. Original scorer has explicit unit or weighted costs; no sclite execution or full format replication.
  • Robust Speech Recognition via Large-Scale Weak Supervision · Read introduction scope, sections2.2/2.3 and3.2, appendixA.1. Visually inspected pages3 and14 including Table5; no benchmark numbers replicated. Pin the ICML2023 version and distinguish paper wording from repository preprocessing/threshold details.
  • Whisper model card at commit86098128 · Read lines10–34 versions/dates,51 data and56–64 limitations. The nine-model prose is stale relative to the added turbo row; some language/hour statistics differ from the paper. Scope dates by month; causal explanations remain author hypotheses. Snapshot2026-08-31; no upstream code execution.

Related topics

No matches. Try a synonym or acronym.

0 results shown

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