keras-team/keras · error · ValueError

Invalid input shape for input

Error message

Invalid input shape for input {x} with name '{self._inputs[i].name}' and path '{path}'. Expected shape {ref_shape}, but input has incompatible shape {x.shape}

What it means

Shape guard in Functional's input standardization: after attempting lenient rank adjustments (squeezing/adding a trailing size-1 axis), the provided tensor's shape still conflicts with the shape the corresponding Input was declared with (e.g. wrong feature dimension). The declared shape is part of the graph contract, so incompatible shapes are rejected before the forward pass.

Solutions

  1. Fix the data so its shape matches the Input shape, including the feature (last) dimension
  2. Rebuild the model with keras.Input(shape=...) matching the actual data shape
  3. Insert an explicit reshape/resize layer rather than relying on the automatic size-1 axis squeeze/expand
Defensive patterns

Strategy: validation

When it happens

Trigger: Thrown at keras/src/models/functional.py:316 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/01a07d1684a28c32. Report an issue: GitHub.

Appendix: source

Thrown at keras/src/models/functional.py:316

            if x is None:
                adjusted.append(x)
                continue
            x_rank = len(x.shape)
            ref_rank = len(ref_shape)
            if x_rank == ref_rank:
                adjusted.append(x)
                continue
            if x_rank == ref_rank + 1:
                if x.shape[-1] == 1:
                    adjusted.append(ops.squeeze(x, axis=-1))
                    continue
            if x_rank == ref_rank - 1:
                if ref_shape[-1] == 1:
                    adjusted.append(ops.expand_dims(x, axis=-1))
                    continue
            flat_paths_and_inputs = tree.flatten_with_path(self._inputs_struct)
            path = ".".join(str(p) for p in flat_paths_and_inputs[i][0])
            raise ValueError(
                f"Invalid input shape for input {x} with name "
                f"'{self._inputs[i].name}' and path '{path}'. Expected shape "
                f"{ref_shape}, but input has incompatible shape {x.shape}"
            )
        # Add back metadata.
        for i in range(len(flat_inputs)):
            if hasattr(flat_inputs[i], "_keras_history"):
                adjusted[i]._keras_history = flat_inputs[i]._keras_history
            mask = backend.get_keras_mask(flat_inputs[i])
            if mask is not None:
                backend.set_keras_mask(adjusted[i], mask)
        return adjusted

    def _standardize_inputs(self, inputs):
        raise_exception = False
        if (
            isinstance(self._inputs_struct, list)
            and len(self._inputs_struct) == 1

View on GitHub (pinned to 7a34a03db6)