keras-team/keras · error · ValueError

Cannot compute sparse categorical crossentropy with `axis={}

Error message

Cannot compute sparse categorical crossentropy with `axis={}` on an output tensor with unknown rank

What it means

Error "Cannot compute sparse categorical crossentropy with `axis={}` on an output tensor with unknown rank" thrown in keras-team/keras.

Source

Thrown at keras/src/legacy/backend.py:1969

        output = tf.clip_by_value(output, epsilon_, 1 - epsilon_)
        output = tf.math.log(output)

    # Permute output so that the last axis contains the logits/probabilities.
    if isinstance(output.shape, (tuple, list)):
        output_rank = len(output.shape)
    else:
        output_rank = output.shape.ndims
    if output_rank is not None:
        axis %= output_rank
        if axis != output_rank - 1:
            permutation = list(
                itertools.chain(
                    range(axis), range(axis + 1, output_rank), [axis]
                )
            )
            output = tf.transpose(output, perm=permutation)
    elif axis != -1:
        raise ValueError(
            "Cannot compute sparse categorical crossentropy with `axis={}` "
            "on an output tensor with unknown rank".format(axis)
        )

    # Try to adjust the shape so that rank of labels = rank of logits - 1.
    output_shape = tf.shape(output)
    target_rank = target.shape.ndims

    update_shape = (
        target_rank is not None
        and output_rank is not None
        and target_rank != output_rank - 1
    )
    if update_shape:
        target = flatten(target)
        output = tf.reshape(output, [-1, output_shape[-1]])

    if ignore_class is not None:

View on GitHub (pinned to 7a34a03db6)

When it happens

Trigger: Thrown at keras/src/legacy/backend.py:1969 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/7a39fad65fea4015. Report an issue: GitHub.