keras-team/keras · error · ValueError

Targets `y_true` are expected to be a tensor of shape…

Error message

Targets `y_true` are expected to be a tensor of shape `(batch_size, max_length)` in integer format. Received: y_true.shape={ops.shape(y_true)}

What it means

Shape guard in the CTC loss: y_true must be a rank-2 integer tensor of shape (batch_size, max_length), where 0 is the blank index. Passing a one-hot / dense label tensor (rank 3) or per-timestep scalars makes len(ops.shape(y_true)) != 2 and trips this check before the CTC algorithm runs.

Solutions

  1. Provide sparse integer labels of shape (batch_size, max_length); use 0 for the blank/pad index (class labels start at 1)
  2. If labels are one-hot encoded, convert with argmax along the class axis first
  3. Pad/truncate label sequences to a single max_length
Defensive patterns

Strategy: validation

When it happens

Trigger: Thrown at keras/src/losses/losses.py:2541 when the library encounters an invalid state.

Common situations: See trigger scenarios.


AI-assisted analysis of keras-team/keras@7a34a03db6 (2026-08-25). Data as JSON: /api/errors/393fcfd702837023. Report an issue: GitHub.

Appendix: source

Thrown at keras/src/losses/losses.py:2541

        focal_bce = weight * focal_bce

    return ops.mean(focal_bce, axis=axis)


@keras_export("keras.losses.ctc")
def ctc(y_true, y_pred):
    """CTC (Connectionist Temporal Classification) loss.

    Args:
        y_true: A tensor of shape `(batch_size, max_length)` containing
            the true labels in integer format. `0` always represents
            the blank/mask index and should not be used for classes.
        y_pred: A tensor of shape `(batch_size, max_length, num_classes)`
            containing logits (the output of your model).
            They should *not* be normalized via softmax.
    """
    if len(ops.shape(y_true)) != 2:
        raise ValueError(
            "Targets `y_true` are expected to be a tensor of shape "
            "`(batch_size, max_length)` in integer format. "
            f"Received: y_true.shape={ops.shape(y_true)}"
        )
    if len(ops.shape(y_pred)) != 3:
        raise ValueError(
            "Logits `y_pred` are expected to be a tensor of shape "
            "`(batch_size, max_length, num_classes)`. "
            f"Received: y_pred.shape={ops.shape(y_pred)}"
        )

    mask_index = 0
    batch_length = ops.shape(y_pred)[0]
    input_length = ops.shape(y_pred)[1]
    input_length = input_length * ops.ones((batch_length,), dtype="int32")
    label_length = ops.cast(
        ops.sum(y_true != mask_index, axis=-1), dtype="int32"
    )

View on GitHub (pinned to 7a34a03db6)