{"record":{"id":"9984f76117fb1187","repo":"keras-team/keras","slug":"input-to-fit-should-have-rank-4-got-array-wi","errorCode":null,"errorMessage":"Input to `.fit()` should have rank 4. Got array with shape: {x.shape}","messagePattern":"Input to `\\.fit\\(\\)` should have rank 4\\. Got array with shape: (.+?)","errorType":"exception","errorClass":"ValueError","httpStatus":null,"severity":"error","filePath":"keras/src/legacy/preprocessing/image.py","lineNumber":1489,"sourceCode":"        When `rescale` is set to a value, rescaling is applied to\n        sample data before computing the internal data stats.\n\n        Args:\n            x: Sample data. Should have rank 4.\n             In case of grayscale data,\n             the channels axis should have value 1, in case\n             of RGB data, it should have value 3, and in case\n             of RGBA data, it should have value 4.\n            augment: Boolean (default: False).\n                Whether to fit on randomly augmented samples.\n            rounds: Int (default: 1).\n                If using data augmentation (`augment=True`),\n                this is how many augmentation passes over the data to use.\n            seed: Int (default: None). Random seed.\n        \"\"\"\n        x = np.asarray(x, dtype=self.dtype)\n        if x.ndim != 4:\n            raise ValueError(\n                \"Input to `.fit()` should have rank 4. Got array with shape: \"\n                + str(x.shape)\n            )\n        if x.shape[self.channel_axis] not in {1, 3, 4}:\n            warnings.warn(\n                \"Expected input to be images (as Numpy array) \"\n                f'following the data format convention \"{self.data_format}'\n                f'\" (channels on axis {self.channel_axis})'\n                \", i.e. expected either 1, 3 or 4 channels on axis \"\n                f\"{self.channel_axis}. However, it was passed an array with\"\n                f\" shape {x.shape} ({x.shape[self.channel_axis]} channels).\"\n            )\n\n        if seed is not None:\n            np.random.seed(seed)\n\n        x = np.copy(x)\n        if self.rescale:","sourceCodeStart":1471,"sourceCodeEnd":1507,"githubUrl":"https://github.com/keras-team/keras/blob/7a34a03db60bf60042242d6a556fc3be119046a5/keras/src/legacy/preprocessing/image.py#L1471-L1507","documentation":"ImageDataGenerator.fit(x) requires a rank-4 array representing a sample of images (N, H, W, C) so it can compute statistics (mean/std/PCA) per channel.","triggerScenarios":"gen.fit(single_image) with shape (H, W, C), or gen.fit(x_flat) with (N, 784).","commonSituations":"Forgetting to batch a single image; passing flattened data.","solutions":["Reshape to (N, H, W, C): x = x.reshape(-1, 28, 28, 1)","For one image: np.expand_dims(img, 0)","Ensure channel count is 1, 3, or 4 (warning otherwise)"],"exampleFix":"// before\ngen.fit(x_train_flat)  # (N, 784)\n// after\ngen.fit(x_train_flat.reshape(-1, 28, 28, 1))\n","handlingStrategy":"validation","validationCode":"x = np.asarray(x)\nassert x.ndim == 4, x.shape","typeGuard":"def rank4(a): return np.asarray(a).ndim == 4","tryCatchPattern":"try: gen.fit(x)\nexcept ValueError as e: if 'rank 4' in str(e): x = np.expand_dims(x, 0) if x.ndim == 3 else x","preventionTips":["Batch single images before fit()","Keep a shared reshape utility for train/val 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"}