keras-team/keras · error · ValueError

The number of dimensions in `start_indices` must match the n

Error message

The number of dimensions in `start_indices` must match the number of dimensions in `inputs`. Received start_indices={start_indices} and inputs.shape={inputs.shape}

What it means

start_indices must list a start offset for every dimension of inputs. Passing fewer or more indices than inputs.ndim makes the slice target ambiguous.

Source

Thrown at keras/src/ops/core.py:448

class Slice(Operation):
    def __init__(self, shape, *, name=None):
        super().__init__(name=name)
        self.shape = shape

    def call(self, inputs, start_indices):
        return backend.core.slice(inputs, start_indices, self.shape)

    def compute_output_spec(self, inputs, start_indices):
        if len(self.shape) != len(inputs.shape):
            raise ValueError(
                "The number of dimensions in `inputs` must match the number of "
                f"dimensions in `shape`. Received inputs.shape={inputs.shape} "
                f"and shape={self.shape}"
            )
        if hasattr(start_indices, "__len__") and len(start_indices) != len(
            inputs.shape
        ):
            raise ValueError(
                "The number of dimensions in `start_indices` must match the "
                "number of dimensions in `inputs`. Received "
                f"start_indices={start_indices} and inputs.shape={inputs.shape}"
            )

        final_shape = []
        for i, (input_dim, slice_dim) in enumerate(
            zip(inputs.shape, self.shape)
        ):
            if slice_dim != -1:
                final_shape.append(slice_dim)
            elif isinstance(start_indices, KerasTensor) or input_dim is None:
                final_shape.append(None)
            else:
                final_shape.append(input_dim - start_indices[i])
        return KerasTensor(final_shape, dtype=inputs.dtype)

View on GitHub (pinned to 7a34a03db6)

Solutions

  1. Pass a tuple with exactly inputs.ndim entries
  2. Build start_indices dynamically: (0,) * x.ndim

Example fix

# before
keras.ops.slice(x, 0, (2,))  # x.ndim == 3

# after
keras.ops.slice(x, (0, 0, 0), (2, 2, 2))
Defensive patterns

Strategy: validation

Validate before calling

if hasattr(start_indices, '__len__'):
    assert len(start_indices) == len(x.shape)

Prevention

When it happens

Trigger: keras.ops.slice(x, (0, 0), ...) on a 3D tensor, or passing an int to a multi-dim tensor

Common situations: Writing generic cropping code that assumes rank 2 for rank 3+ tensors

Related errors


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