{"record":{"id":"679a82df79e0731e","repo":"keras-team/keras","slug":"input-data-in-numpyarrayiterator-should-have-ran","errorCode":null,"errorMessage":"Input data in `NumpyArrayIterator` should have rank 4. You passed an array with shape {self.x.shape}","messagePattern":"Input data in `NumpyArrayIterator` should have rank 4\\. You passed an array with shape (.+?)","errorType":"exception","errorClass":"ValueError","httpStatus":null,"severity":"error","filePath":"keras/src/legacy/preprocessing/image.py","lineNumber":616,"sourceCode":"                    \"sorted by the label, you might want \"\n                    \"to shuffle them.\"\n                )\n\n            if subset == \"validation\":\n                x = x[:split_idx]\n                x_misc = [np.asarray(xx[:split_idx]) for xx in x_misc]\n                if y is not None:\n                    y = y[:split_idx]\n            else:\n                x = x[split_idx:]\n                x_misc = [np.asarray(xx[split_idx:]) for xx in x_misc]\n                if y is not None:\n                    y = y[split_idx:]\n\n        self.x = np.asarray(x, dtype=self.dtype)\n        self.x_misc = x_misc\n        if self.x.ndim != 4:\n            raise ValueError(\n                \"Input data in `NumpyArrayIterator` \"\n                \"should have rank 4. You passed an array \"\n                f\"with shape {self.x.shape}\"\n            )\n        channels_axis = 3 if data_format == \"channels_last\" else 1\n        if self.x.shape[channels_axis] not in {1, 3, 4}:\n            warnings.warn(\n                f\"NumpyArrayIterator is set to use the data format convention\"\n                f' \"{data_format}\" (channels on axis {channels_axis})'\n                \", i.e. expected either 1, 3, or 4 channels \"\n                f\"on axis {channels_axis}. \"\n                f\"However, it was passed an array with shape {self.x.shape}\"\n                f\" ({self.x.shape[channels_axis]} channels).\"\n            )\n        if y is not None:\n            self.y = np.asarray(y)\n        else:\n            self.y = None","sourceCodeStart":598,"sourceCodeEnd":634,"githubUrl":"https://github.com/keras-team/keras/blob/7a34a03db60bf60042242d6a556fc3be119046a5/keras/src/legacy/preprocessing/image.py#L598-L634","documentation":"NumpyArrayIterator requires a rank-4 array (batch, rows, cols, channels) or (batch, channels, rows, cols). Arrays of other ranks are rejected.","triggerScenarios":"Passing a single image (rank 3), a flat vector of pixels (rank 2), or a batch of 5D video frames to gen.flow(x, ...).","commonSituations":"Forgetting np.expand_dims(x, 0) for a single image; loading raw MNIST flattened to (60000, 784); wrong data_format vs array layout.","solutions":["Reshape x to (N, H, W, C) e.g. x[..., np.newaxis] for grayscale","For a single image use np.expand_dims(img, axis=0)","Check data_format ('channels_last' default) matches your axis order"],"exampleFix":"// before\ngen.flow(x_train_flat, y_train)  # (N, 784)\n// after\nx = x_train_flat.reshape(-1, 28, 28, 1)\ngen.flow(x, y_train)\n","handlingStrategy":"validation","validationCode":"x = np.asarray(x)\nassert x.ndim == 4, x.shape","typeGuard":"def is_rank4(a): return np.asarray(a).ndim == 4","tryCatchPattern":"try: gen.flow(x, y)\nexcept ValueError as e: if 'rank 4' in str(e): x = x.reshape(x.shape[0], *x.shape[1:]) if x.ndim==3 else ...","preventionTips":["Standardize pipelines to NHWC upfront","Assert ndim==4 right after loading data"],"tags":["keras","numpy","tensor-rank"],"backgroundTag":"input-shape-mismatch","analyzedSha":"7a34a03db60bf60042242d6a556fc3be119046a5","analyzedAt":"2026-08-25T21:25:25.994Z","schemaVersion":2},"datasetVersion":"2026-08-26T02:17:13.382Z"}