keras-team/keras · error · ValueError

Expected the input image to be rank 3 or 4. Received inputs.

Error message

Expected the input image to be rank 3 or 4. Received inputs.shape={images_shape}

What it means

RandomErasing.get_random_transformation only handles single images (rank 3: H, W, C) or batched images (rank 4: N, H, W, C). Any other rank raises this ValueError at call time, i.e. the moment data flows through the layer during training or transform().

Source

Thrown at keras/src/layers/preprocessing/image_preprocessing/random_erasing.py:230

        return fill_value

    def get_random_transformation(self, data, training=True, seed=None):
        if not training:
            return None

        if isinstance(data, dict):
            images = data["images"]
        else:
            images = data

        images_shape = self.backend.shape(images)
        rank = len(images_shape)
        if rank == 3:
            batch_size = 1
        elif rank == 4:
            batch_size = images_shape[0]
        else:
            raise ValueError(
                "Expected the input image to be rank 3 or 4. Received "
                f"inputs.shape={images_shape}"
            )

        image_height = images_shape[self.height_axis]
        image_width = images_shape[self.width_axis]

        seed = seed or self._get_seed_generator(self.backend._backend)

        mix_weight = self.backend.random.uniform(
            shape=(batch_size, 2),
            minval=self.scale[0],
            maxval=self.scale[1],
            dtype=self.compute_dtype,
            seed=seed,
        )

        mix_weight = self.backend.numpy.sqrt(mix_weight)

View on GitHub (pinned to 7a34a03db6)

Solutions

  1. Add a channel/batch dim: use keras.ops.expand_dims(img, -1) for rank-2 grayscale, or expand_dims(img, 0) to make a rank-3 single image
  2. Keep batches rank-4 of shape (batch, height, width, channels)
  3. For video, reshape frames to rank-4 and loop, or write a custom layer

Example fix

# before
out = random_erasing(images[0, :, :])  # rank 2
# after
out = random_erasing(keras.ops.expand_dims(images[0], -1))  # rank 3
Defensive patterns

Strategy: validation

Validate before calling

import keras
rank = len(images.shape)
if rank == 2:
    images = keras.ops.expand_dims(images, -1)
elif rank != 3 and rank != 4:
    raise ValueError(f"need rank 3 or 4 input, got rank {rank}")

Type guard

def is_image_batch(t) -> bool:
    return len(getattr(t, "shape", ())) in (3, 4)

Try / catch

try:
    out = layer(images)
except ValueError as e:
    raise ValueError(f"reshape to (N,H,W,C) or (H,W,C): {e}") from e

Prevention

When it happens

Trigger: Feeding a single un-batched 2-D grayscale slice images[i, :, :]; passing a rank-5 video tensor (frames, N, H, W, C); passing an un-squeezed 2-D array of shape (28, 28).

Common situations: Slicing batches incorrectly before augmentation; forgetting keras.ops.expand_dims on grayscale data; applying image preprocessing layers to video/multi-frame pipelines where extra leading dims exist.

Related errors


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