keras-team/keras · error · ValueError
Input to `.fit()` should have rank 4. Got array with shape:
Error message
Input to `.fit()` should have rank 4. Got array with shape: {x.shape} What it means
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.
Source
Thrown at keras/src/legacy/preprocessing/image.py:1489
When `rescale` is set to a value, rescaling is applied to
sample data before computing the internal data stats.
Args:
x: Sample data. Should have rank 4.
In case of grayscale data,
the channels axis should have value 1, in case
of RGB data, it should have value 3, and in case
of RGBA data, it should have value 4.
augment: Boolean (default: False).
Whether to fit on randomly augmented samples.
rounds: Int (default: 1).
If using data augmentation (`augment=True`),
this is how many augmentation passes over the data to use.
seed: Int (default: None). Random seed.
"""
x = np.asarray(x, dtype=self.dtype)
if x.ndim != 4:
raise ValueError(
"Input to `.fit()` should have rank 4. Got array with shape: "
+ str(x.shape)
)
if x.shape[self.channel_axis] not in {1, 3, 4}:
warnings.warn(
"Expected input to be images (as Numpy array) "
f'following the data format convention "{self.data_format}'
f'" (channels on axis {self.channel_axis})'
", i.e. expected either 1, 3 or 4 channels on axis "
f"{self.channel_axis}. However, it was passed an array with"
f" shape {x.shape} ({x.shape[self.channel_axis]} channels)."
)
if seed is not None:
np.random.seed(seed)
x = np.copy(x)
if self.rescale:View on GitHub (pinned to 7a34a03db6)
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)
Example fix
// before gen.fit(x_train_flat) # (N, 784) // after gen.fit(x_train_flat.reshape(-1, 28, 28, 1))
Defensive patterns
Strategy: validation
Validate before calling
x = np.asarray(x) assert x.ndim == 4, x.shape
Type guard
def rank4(a): return np.asarray(a).ndim == 4
Try / catch
try: gen.fit(x) except ValueError as e: if 'rank 4' in str(e): x = np.expand_dims(x, 0) if x.ndim == 3 else x
Prevention
- Batch single images before fit()
- Keep a shared reshape utility for train/val data
When it happens
Trigger: gen.fit(single_image) with shape (H, W, C), or gen.fit(x_flat) with (N, 784).
Common situations: Forgetting to batch a single image; passing flattened data.
Related errors
- Input data in `NumpyArrayIterator` should have rank 4. You p
- Found bounding_boxes['boxes'].shape={boxes_shape} and expect
- Found bounding_boxes['boxes'].shape={boxes_shape} and expect
- Expected `bounding_boxes['boxes']` to have rank 2 or 3, with
- Expected the input image to be rank 3 or 4. Received inputs.
AI-assisted analysis of keras-team/keras@7a34a03db6 (2026-08-25).
Data as JSON: /api/errors/9984f76117fb1187.
Report an issue: GitHub.