keras-team/keras · error · ValueError

Cannot convert ' ' to a shape. Negative dimensions are not…

Error message

Cannot convert '{shape}' to a shape. Negative dimensions are not allowed.

What it means

Raised by standardize_shape after a dimension was cast to int but the result is negative. Shapes cannot have negative dimensions, so values like -1 (the 'infer this dim' reshape convention) are rejected when used inside a variable shape.

Solutions

  1. Fix the dimension to a non-negative integer; -1 is not a valid shape entry here.
  2. Guard computed dims with max(0, d) or assert d >= 0 before use.
  3. Use None (where the API allows) for dynamic dims, never negative numbers.
Defensive patterns

Strategy: validation

When it happens

Trigger: Thrown at keras/src/backend/common/variables.py:641 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/b0717a6812348683. Report an issue: GitHub.

Appendix: source

Thrown at keras/src/backend/common/variables.py:641

            continue

        # Reject these even if they can be cast to int successfully.
        if isinstance(d, (str, float)):
            raise ValueError(
                f"Cannot convert '{shape}' to a shape. "
                f"Found invalid dimension '{d}' of type '{type(d)}'. "
            )

        try:
            # Cast numpy scalars, tf constant tensors, etc.
            d = int(d)
        except Exception as e:
            raise ValueError(
                f"Cannot convert '{shape}' to a shape. "
                f"Found invalid dimension '{d}' of type '{type(d)}'. "
            ) from e
        if d < 0:
            raise ValueError(
                f"Cannot convert '{shape}' to a shape. "
                "Negative dimensions are not allowed."
            )
        standardized_shape.append(d)

    # This also turns subclasses of `tuple` (e.g. `torch.Size`) to plain tuple.
    return tuple(standardized_shape)


def shape_equal(a_shape, b_shape):
    """Return whether a_shape == b_shape (allows None entries)."""
    if len(a_shape) != len(b_shape):
        return False
    for e1, e2 in zip(a_shape, b_shape):
        if e1 is not None and e2 is not None and e1 != e2:
            return False
    return True

View on GitHub (pinned to 7a34a03db6)