CTC Loss is computed in the following steps.
- Add one blank to the output layer: Use a softmax layer with β£Lβ£+1 outputs, the set of characters (labels) L plus the blank. yktβ is the probability of outputting symbol k at time t.
- Take a path's probability as the product of per-time-step probabilities: The probability of a path Ο of length T is the product of the outputs, treating each time step as independent (Eq. (2) of the paper).
p(Οβ£x)=t=1βTβyΟtβtβ
- Collapse paths into strings: The mapping B processes a path by first "merging repeated consecutive symbols into one" and then "removing blanks." In the paper's example, B(aβabβ)=B(βaaββabb)=aab (β is the blank).
- Sum the probabilities of all paths that collapse to the target (Eq. (3)).
p(lβ£x)=ΟβBβ1(l)ββp(Οβ£x)
- Do the summation by dynamic programming on a lattice: The number of paths grows exponentially with T, so build a lattice with the sequence lβ² (length 2β£lβ£+1), the target l with blanks inserted at both ends and between characters, on one axis and time on the other. The forward variable Ξ±tβ(s) (the total probability of paths that have reached position s of lβ² by time t) is computed in time order with the following formula (Eqs. (6) and (7)).
Ξ±tβ(s)={(Ξ±tβ1β(s)+Ξ±tβ1β(sβ1))ylsβ²βtβ(Ξ±tβ1β(s)+Ξ±tβ1β(sβ1)+Ξ±tβ1β(sβ2))ylsβ²βtββ(lsβ²βΒ isΒ blankΒ orΒ lsβ2β²β=lsβ²β)(otherwise)β
Paths start at the blank or the first character (Ξ±1β(1)=yb1β, Ξ±1β(2)=yl1β1β) and end at the last character or the last blank.
p(lβ£x)=Ξ±Tβ(β£lβ²β£)+Ξ±Tβ(β£lβ²β£β1)
- Use the negative log-likelihood as the loss: To maximize the log probability of the targets in the training data, minimize βlnp(zβ£x) (Eq. (12)). Combining it with the backward variable Ξ²tβ(s), computed the same way from the end, gives the gradient with respect to the output at each time step, so the network can be trained with ordinary backpropagation through time.
In the lattice of the figure at the top, the bold line is an example path (C,C,β,A,A,β,T,T). From each node there are three moves: stay in the same row, move down one row, or move down two rows (skipping a blank). However, a blank cannot move down two rows, and for targets with repeated characters (for example, the aa in aab), the blank between them cannot be skipped, because B would otherwise merge them into a single character.
In practice, the product of probabilities quickly becomes too small and rounds to 0 (underflow). The paper shows how to keep the values in range by dividing by the sum of Ξ±tβ at each time step, and to obtain lnp(lβ£x) by adding up the logarithms of those sums. PyTorch's nn.CTCLoss also takes log probabilities rather than probabilities.