keras-team/keras · error · ValueError

Argument `output` must be at least rank 1. Received…

Error message

Argument `output` must be at least rank 1. Received: output.shape={output.shape}

What it means

Raised by sparse_categorical_crossentropy in the JAX backend when the `output` tensor has rank 0 (a scalar). Cross-entropy needs at least one axis to reduce over (`axis` defaults to -1), so a scalar prediction tensor is invalid. Pass tensors of rank >= 1, typically (batch,) or (batch, classes).

Solutions

  1. Pass predictions of shape (num_classes,) or (batch, num_classes).
  2. Expand scalar outputs: keras.ops.expand_dims(output, -1).
  3. Targets may be (batch, 1) or (batch,) — they are squeezed automatically; the output must carry the class axis.
Defensive patterns

Strategy: validation

When it happens

Trigger: Thrown at keras/src/backend/jax/nn.py:998 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/f3209be4d47a6630. Report an issue: GitHub.

Appendix: source

Thrown at keras/src/backend/jax/nn.py:998

        )

    if from_logits:
        log_prob = jax.nn.log_softmax(output, axis=axis)
    else:
        output = output / jnp.sum(output, axis, keepdims=True)
        output = jnp.clip(output, backend.epsilon(), 1.0 - backend.epsilon())
        log_prob = jnp.log(output)
    return -jnp.sum(target * log_prob, axis=axis)


def sparse_categorical_crossentropy(target, output, from_logits=False, axis=-1):
    target = jnp.array(target, dtype="int32")
    output = jnp.array(output)
    if len(target.shape) == len(output.shape) and target.shape[-1] == 1:
        target = jnp.squeeze(target, axis=-1)

    if len(output.shape) < 1:
        raise ValueError(
            "Argument `output` must be at least rank 1. "
            "Received: "
            f"output.shape={output.shape}"
        )
    if target.shape != output.shape[:-1]:
        raise ValueError(
            "Arguments `target` and `output` must have the same shape "
            "up until the last dimension: "
            f"target.shape={target.shape}, output.shape={output.shape}"
        )
    if from_logits:
        log_prob = jax.nn.log_softmax(output, axis=axis)
    else:
        output = output / jnp.sum(output, axis, keepdims=True)
        output = jnp.clip(output, backend.epsilon(), 1.0 - backend.epsilon())
        log_prob = jnp.log(output)
    target = jnn.one_hot(target, output.shape[axis], axis=axis)
    return -jnp.sum(target * log_prob, axis=axis)

View on GitHub (pinned to 7a34a03db6)