{"record":{"id":"dc4e24c8c19fecfc","repo":"keras-team/keras","slug":"expected-the-input-image-to-be-rank-3-or-4-receiv-dc4e24","errorCode":null,"errorMessage":"Expected the input image to be rank 3 or 4. Received inputs.shape={images_shape}","messagePattern":"Expected the input image to be rank 3 or 4\\. Received inputs\\.shape=(.+?)","errorType":"exception","errorClass":"ValueError","httpStatus":null,"severity":"error","filePath":"keras/src/layers/preprocessing/image_preprocessing/random_erasing.py","lineNumber":230,"sourceCode":"        return fill_value\n\n    def get_random_transformation(self, data, training=True, seed=None):\n        if not training:\n            return None\n\n        if isinstance(data, dict):\n            images = data[\"images\"]\n        else:\n            images = data\n\n        images_shape = self.backend.shape(images)\n        rank = len(images_shape)\n        if rank == 3:\n            batch_size = 1\n        elif rank == 4:\n            batch_size = images_shape[0]\n        else:\n            raise ValueError(\n                \"Expected the input image to be rank 3 or 4. Received \"\n                f\"inputs.shape={images_shape}\"\n            )\n\n        image_height = images_shape[self.height_axis]\n        image_width = images_shape[self.width_axis]\n\n        seed = seed or self._get_seed_generator(self.backend._backend)\n\n        mix_weight = self.backend.random.uniform(\n            shape=(batch_size, 2),\n            minval=self.scale[0],\n            maxval=self.scale[1],\n            dtype=self.compute_dtype,\n            seed=seed,\n        )\n\n        mix_weight = self.backend.numpy.sqrt(mix_weight)","sourceCodeStart":212,"sourceCodeEnd":248,"githubUrl":"https://github.com/keras-team/keras/blob/7a34a03db60bf60042242d6a556fc3be119046a5/keras/src/layers/preprocessing/image_preprocessing/random_erasing.py#L212-L248","documentation":"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().","triggerScenarios":"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).","commonSituations":"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.","solutions":["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","Keep batches rank-4 of shape (batch, height, width, channels)","For video, reshape frames to rank-4 and loop, or write a custom layer"],"exampleFix":"# before\nout = random_erasing(images[0, :, :])  # rank 2\n# after\nout = random_erasing(keras.ops.expand_dims(images[0], -1))  # rank 3","handlingStrategy":"validation","validationCode":"import keras\nrank = len(images.shape)\nif rank == 2:\n    images = keras.ops.expand_dims(images, -1)\nelif rank != 3 and rank != 4:\n    raise ValueError(f\"need rank 3 or 4 input, got rank {rank}\")","typeGuard":"def is_image_batch(t) -> bool:\n    return len(getattr(t, \"shape\", ())) in (3, 4)","tryCatchPattern":"try:\n    out = layer(images)\nexcept ValueError as e:\n    raise ValueError(f\"reshape to (N,H,W,C) or (H,W,C): {e}\") from e","preventionTips":["Expand dims on grayscale/unbatched inputs before preprocessing layers","Assert tensor rank in data pipelines feeding image layers"],"tags":["keras","preprocessing","tensor-shape","rank-validation"],"backgroundTag":"invalid-tensor-rank","analyzedSha":"7a34a03db60bf60042242d6a556fc3be119046a5","analyzedAt":"2026-08-25T21:25:25.994Z","schemaVersion":2},"datasetVersion":"2026-08-26T02:17:13.382Z"}