keras-team/keras · error · ValueError

{self.__class__.__name__} was passed incompatible inputs. Fo

Error message

{self.__class__.__name__} was passed incompatible inputs. For input '{x_ref.name}', expected shape {x_ref.shape}, but received instead a tensor with shape {x.shape}.

What it means

A Functional (keras.ops.Function) layer built from symbolic inputs validates at call time that each incoming tensor has the same rank (same number of axes) as the KerasTensor input it was traced with. It throws this ValueError when the number of dimensions differs, because the underlying op graph was compiled for a fixed input structure.

Source

Thrown at keras/src/ops/function.py:239

                raise ValueError(
                    f"Output with path `{path}` is not connected to `inputs`"
                )
            output_tensors.append(tensor_dict[id(x)])

        return tree.pack_sequence_as(self._outputs_struct, output_tensors)

    def _assert_input_compatibility(self, inputs):
        try:
            tree.assert_same_structure(inputs, self._inputs_struct)
        except ValueError:
            raise ValueError(
                "Function was called with an invalid input structure. "
                f"Expected input structure: {self._inputs_struct}\n"
                f"Received input structure: {inputs}"
            )
        for x, x_ref in zip(tree.flatten(inputs), self._inputs):
            if len(x.shape) != len(x_ref.shape):
                raise ValueError(
                    f"{self.__class__.__name__} was passed "
                    f"incompatible inputs. For input '{x_ref.name}', "
                    f"expected shape {x_ref.shape}, but received "
                    f"instead a tensor with shape {x.shape}."
                )
            for dim, ref_dim in zip(x.shape, x_ref.shape):
                if ref_dim is not None and dim is not None:
                    if dim != ref_dim:
                        raise ValueError(
                            f"{self.__class__.__name__} was passed "
                            f"incompatible inputs. For input '{x_ref.name}', "
                            f"expected shape {x_ref.shape}, but received "
                            f"instead a tensor with shape {x.shape}."
                        )


def make_node_key(op, node_index):
    return f"{id(op)}_ib-{node_index}"

View on GitHub (pinned to 7a34a03db6)

Solutions

  1. Compare the 'expected shape' in the message with the 'received shape' and add or remove axes on your input (e.g. x = x[..., None] or np.expand_dims(x, 0)) so both have the same number of dimensions
  2. If the data genuinely changed rank, re-trace/rebuild the function or model with a input matching the new rank
  3. Check for an accidental batch dimension added/removed by your data pipeline (tf.data .batch(), dataset.unbatch(), etc.)

Example fix

# before
y = fn(x)  # x.shape=(32, 28, 28) but fn traced with (None, 28, 28, 1)

# after
x = np.expand_dims(x, -1)  # (32, 28, 28, 1)
y = fn(x)
Defensive patterns

Strategy: validation

Validate before calling

rank = len(getattr(x, 'shape', ()))
if rank != len(fn_input_shape):
    raise ValueError(f'input rank {rank} != expected {len(fn_input_shape)}')

Type guard

def matches_traced_rank(x, ref_shape) -> bool:
    s = tuple(x.shape)
    return len(s) == len(ref_shape)

Try / catch

try:
    y = fn(x)
except ValueError as e:
    if 'incompatible inputs' in str(e):
        x = np.expand_dims(x, -1)
        y = fn(x)
    else:
        raise

Prevention

When it happens

Trigger: Calling a Functional/ops.Function (or a model built via keras.ops on symbolic tensors) with an input whose ndim differs from the traced ndim, e.g. traced with shape (None, 28, 28) but called with (None, 28, 28, 1), or passing a single image (3 dims) where a batch (4 dims) was traced.

Common situations: Adding/removing a channels dimension before calling a saved or traced model; switching between channels_last/channels_first pipelines; feeding grayscale vs RGB; reusing a traced preprocessing function on data with an extra batch axis.

Related errors


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