Decode a CTC output with best-path greedy decoding

Speech recognisers trained with CTC emit one probability row per audio frame, including a special blank symbol. Greedy decoding turns those frames into a label sequence.

Write ctc_greedy(probs, blank=0). probs has shape (T, C). Steps:
1. Take the argmax class of each frame (lowest index on ties).
2. Merge consecutive repeats into one.
3. Remove blanks.
Return the result as a list of ints (possibly empty).

Order matters: a blank between two equal labels keeps them separate. Frames [a, a, blank, a] decode to [a, a].

Signaturedef ctc_greedy(probs, blank=0)

Example

frame argmaxes [1, 1, 0, 1, 2, 2] with blank 0 give [1, 1, 2].

Understand the idea

A CTC model outputs one probability row per audio frame, including a special blank. A spoken letter usually lasts several frames, so the model repeats it, and it uses blanks to mark that two identical letters are really separate. Greedy decoding picks the best class per frame, merges runs of the same class, then deletes the blanks, in that order. Worked example with blank 0: frame argmaxes [0, 2, 2, 0, 2, 3, 3]. Merge repeats: [0, 2, 0, 2, 3]. Remove blanks: [2, 2, 3]. The blank between the two 2s kept them apart. If you deleted blanks first you would get [2, 2, 2, 3, 3], which merges to [2, 3], losing a letter, the way 'book' turns into 'bok'. Rule: argmax per row (lowest index on ties), collapse consecutive duplicates, drop every blank, return a list (it can be empty). This is the fast decoder used for speech recognition and handwriting models when no language model rescoring is needed.

solution.pyPython idle
Ctrl/Cmd + Enter runs sample tests

Run checks the first 2 tests. Submit checks all 4.

  • Sample 1: examplectc_greedy(_frames([1, 1, 0, 1, 2, 2]))
  • Sample 2: all blankctc_greedy(_frames([0, 0, 0]))
  • Test 3: double letter needs blankctc_greedy(_frames([3, 0, 3, 3, 0, 0, 2, 1, 1]))
  • Test 4: custom blank indexctc_greedy(_frames([2, 3, 3, 2, 1, 2, 1]), blank=2)