keras-team/keras · error · ValueError

First dim of `coordinates` must be the same as the rank of `

Error message

First dim of `coordinates` must be the same as the rank of `inputs`. Received inputs with shape: {inputs.shape} and coordinate leading dim of {coordinates.shape[0]}

What it means

keras.ops.image.map_coordinates samples inputs at arbitrary coordinates, where coordinates must be a tensor of shape (input_rank, ...) — one coordinate vector per input axis along the leading dim. The output-spec check raises when coordinates.shape[0] != len(inputs.shape), i.e. you supplied too few or too many coordinate components.

Source

Thrown at keras/src/ops/image.py:1465

class MapCoordinates(Operation):
    def __init__(self, order, fill_mode="constant", fill_value=0, *, name=None):
        super().__init__(name=name)
        self.order = order
        self.fill_mode = fill_mode
        self.fill_value = fill_value

    def call(self, inputs, coordinates):
        return backend.image.map_coordinates(
            inputs,
            coordinates,
            order=self.order,
            fill_mode=self.fill_mode,
            fill_value=self.fill_value,
        )

    def compute_output_spec(self, inputs, coordinates):
        if coordinates.shape[0] != len(inputs.shape):
            raise ValueError(
                "First dim of `coordinates` must be the same as the rank of "
                "`inputs`. "
                f"Received inputs with shape: {inputs.shape} and coordinate "
                f"leading dim of {coordinates.shape[0]}"
            )
        if len(coordinates.shape) < 2:
            raise ValueError(
                "Invalid coordinates rank: expected at least rank 2."
                f" Received input with shape: {coordinates.shape}"
            )
        return KerasTensor(coordinates.shape[1:], dtype=inputs.dtype)


@keras_export("keras.ops.image.map_coordinates")
def map_coordinates(
    inputs, coordinates, order, fill_mode="constant", fill_value=0
):
    """Map the input array to new coordinates by interpolation.

View on GitHub (pinned to 7a34a03db6)

Solutions

  1. Stack coordinate components on axis 0: coords = np.stack([ys, xs], axis=0) for a rank-2 image, plus one component per extra input axis
  2. Ensure coords.shape[0] equals the full rank of inputs (include the channel axis if inputs is rank 3)
  3. If you only care about spatial sampling, sample per channel or drop the channel axis from inputs

Example fix

# before
coords = np.stack([ys, xs], axis=-1)  # (N, 2)
map_coordinates(img, coords)          # img rank 3 -> error

# after
coords = np.stack([ys_c, xs_c, cs], axis=0)  # (3, N) matching img rank 3
map_coordinates(img, coords)
Defensive patterns

Strategy: validation

Validate before calling

assert coordinates.shape[0] == len(inputs.shape), 'coords leading dim must equal input rank'

Type guard

def coords_rank_ok(inputs, coordinates) -> bool:
    return coordinates.shape[0] == len(inputs.shape)

Prevention

When it happens

Trigger: map_coordinates(img, coords) where img has rank 3 (H,W,C) but coords.shape[0] is 2 (only y,x) or 4; passing per-pixel (row, col) pairs stacked along the last axis instead of the first.

Common situations: Coming from scipy.ndimage.map_coordinates (same leading-dim convention but users wrap coords wrongly); building coordinate grids with meshgrid and stacking on axis=-1; adding/removing a batch or channel axis after writing the coordinate code.

Related errors


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