Keras CTC `Loss` input
ML System Design practice on Codemia
Design recommenders, ranking systems and training pipelines the way ML interviews actually ask for them, with worked solutions.
Introduction
CTC loss is used when a model predicts a sequence over time but the exact alignment between time steps and target labels is unknown. The idea is conceptually elegant, but most implementation bugs come from shape bookkeeping rather than from the mathematics of CTC itself. In Keras, the essential task is to pass predictions, target labels, input lengths, and label lengths in the exact form the loss expects.
The Four Inputs You Must Get Right
A typical Keras or TensorFlow CTC setup needs four pieces of data for each batch:
- '
y_pred: model outputs across time steps' - '
y_true: padded target label ids' - '
input_length: number of valid model time steps per example' - '
label_length: number of valid target labels per example'
The batch dimension must align across all four tensors. If one of them is off by even one axis, training fails or silently learns the wrong thing.
Common Shape Convention in Keras
With tf.keras.backend.ctc_batch_cost, the usual shape contract is:
- '
y_pred:(batch_size, time_steps, num_classes)' - '
y_true:(batch_size, max_label_length)' - '
input_length:(batch_size, 1)' - '
label_length:(batch_size, 1)'
A minimal working example looks like this:
The label tensor can be padded, but label_length tells CTC which positions are real and which are just filler.
The Blank Class Is Required
CTC needs one extra output class for the blank symbol. If your vocabulary contains N actual labels, the network output must usually contain N + 1 classes.
For example, if you have digits 0 through 9, the output layer needs 11 units when using a CTC blank:
If the blank class is missing, the loss and the decoder no longer match the CTC formulation.
input_length Is About Model Time Steps
A very common mistake is setting input_length equal to the target length. That is wrong. input_length describes how many valid time steps the model produced for each item after all convolution, pooling, or subsampling layers.
If a CNN or pooling stage shrinks the time dimension before the recurrent stack, you must compute the reduced length correctly. Otherwise, CTC tries to align labels against a time axis that does not actually exist.
Padding Is Allowed, but Lengths Must Be Honest
Target labels are usually padded to a uniform width so they fit in a batch tensor. That is normal. The important part is that label_length gives the true number of labels before padding.
For example, if two samples are [1, 2] and [2, 3, 4], the padded batch might be:
but the true label lengths are [2, 3]. If you lie about those lengths, the loss interprets padding as real labels and the training signal becomes invalid.
Debug One Batch Before Training
CTC is much easier to debug on one batch than during a long training run. Print the shapes and lengths early.
That small check often catches the real problem immediately: swapped axes, wrong output width, missing blank class, or an incorrect length calculation after downsampling.
Common Pitfalls
The most common mistake is confusing input_length with label_length. They measure completely different things.
Another mistake is forgetting the extra blank class in the output layer. That makes the entire CTC setup inconsistent.
Developers also pad labels but fail to supply the correct label_length, so the loss interprets padded tokens as part of the target sequence.
Summary
- Keras CTC loss needs predictions, labels, input lengths, and label lengths.
- '
y_predis typically shaped(batch_size, time_steps, num_classes).' - The output classes must include the CTC blank token.
- '
input_lengthdescribes model time steps, not target length.' - Most CTC failures are shape or length bookkeeping errors, not problems with the loss formula itself.
Related reading
- Keras CuDNNLSTM implicit activation function?
- Keras Custom layer without inputs
- Keras custom loss function Accessing current input pattern
- Keras custom loss function Accessing current input pattern
- Keras custom decision threshold for precision and recall
- Keras custom decision threshold for precision and recall
- Keras custom loss function to ignore false negatives of a specific class during semantic segmentation?
- Keras Custom loss function to pass arguments other than y_true and y_pred
.png&w=3840&q=75)
Tackling System Design Interview Problems
A short course that equips you with the skills to approach system design interviews methodically.
Start the free courseTrack what you have practised
A free account saves your progress, solutions and study plan across every problem on Codemia.
ML System Design practice on Codemia
Design recommenders, ranking systems and training pipelines the way ML interviews actually ask for them, with worked solutions.