keras-team/keras · error · ValueError

`patches` has unexpected rank for

Error message

`patches` has unexpected rank for {'3D' if self.is_3d else '2D'} reconstruction. Expected {expected_ndim_unbatched} (unbatched) or {expected_ndim_batched} (batched). Received shape: {patches.shape}

What it means

Raised during reconstruct_patches when the patches tensor rank doesn't match either the batched or unbatched layout expected for 2D (3/4-D) or 3D (4/5-D) reconstruction, indicating a malformed or transposed patches array.

Solutions

  1. Provide patches from extract_patches in (batch, grid..., patch_volume) layout
  2. Add/remove the batch dimension to match unbatched or batched calling convention
  3. Verify you're using the correct 2D vs 3D variant for your data
Defensive patterns

Strategy: validation

When it happens

Trigger: Thrown at keras/src/ops/image.py:995 when the library encounters an invalid state.

Common situations: See trigger scenarios.


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

Appendix: source

Thrown at keras/src/ops/image.py:995

        for s in self.size:
            patch_volume *= s
        channels_out = None if flat is None else flat // patch_volume

        if self.is_3d:
            expected_ndim_batched = 5
            expected_ndim_unbatched = 4
            spatial = self.output_size  # (D, H, W)
        else:
            expected_ndim_batched = 4
            expected_ndim_unbatched = 3
            spatial = self.output_size  # (H, W)

        if original_ndim == expected_ndim_batched:
            batch = patches_shape[0]
        elif original_ndim == expected_ndim_unbatched:
            batch = None
        else:
            raise ValueError(
                f"`patches` has unexpected rank for "
                f"{'3D' if self.is_3d else '2D'} reconstruction. "
                f"Expected {expected_ndim_unbatched} (unbatched) or "
                f"{expected_ndim_batched} (batched). "
                f"Received shape: {patches.shape}"
            )

        if flat is not None and flat % patch_volume != 0:
            raise ValueError(
                f"`patches` last dim ({flat}) is not divisible by "
                f"prod(size) ({patch_volume})."
            )

        if self.data_format == "channels_last":
            grid_offset = 1 if original_ndim == expected_ndim_batched else 0
            grid = patches_shape[grid_offset : grid_offset + len(self.size)]
        else:
            # channels_first: the grid dims are the trailing dims,

View on GitHub (pinned to 7a34a03db6)