keras-team/keras · error · ValueError
Arguments `target` and `output` must have the same shape up…
Error message
Arguments `target` and `output` must have the same shape up until the last dimension: target.shape={target.shape}, output.shape={output.shape} What it means
Raised by the NumPy backend's categorical crossentropy implementation when the shape guard that compares `target` and `output` finds they disagree on any dimension except the last one. The last axis of `output` holds class probabilities while `target` may be one-hot along that same axis, so all leading (batch/intermediate) dimensions must line up exactly; a mismatch means the labels tensor does not broadcast against the predictions tensor.
Solutions
- Reshape or re-encode `target` so every dimension except the last matches `output` (e.g. one-hot encode integer labels with keras.ops.one_hot to the same class count)
- Remove a spurious trailing axis of size 1 on `target` (squeeze it) when labels were stored as (..., 1) instead of (..., num_classes)
- Check for accidental broadcasting upstream in the model that changed the batch or intermediate dimensions of the predictions before the loss was computed
Defensive patterns
Strategy: validation
When it happens
Trigger: Thrown at keras/src/backend/numpy/nn.py:899 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/437102ea6c7e35ea.
Report an issue: GitHub.
Appendix: source
Thrown at keras/src/backend/numpy/nn.py:899
output = np.clip(output, backend.epsilon(), 1.0 - backend.epsilon())
log_prob = np.log(output)
return -np.sum(target * log_prob, axis=axis)
def sparse_categorical_crossentropy(target, output, from_logits=False, axis=-1):
target = np.array(target, dtype="int32")
output = np.array(output)
if len(target.shape) == len(output.shape) and target.shape[-1] == 1:
target = np.squeeze(target, axis=-1)
if len(output.shape) < 1:
raise ValueError(
"Argument `output` must be at least rank 1. "
"Received: "
f"output.shape={output.shape}"
)
if target.shape != output.shape[:-1]:
raise ValueError(
"Arguments `target` and `output` must have the same shape "
"up until the last dimension: "
f"target.shape={target.shape}, output.shape={output.shape}"
)
if from_logits:
log_prob = log_softmax(output, axis=axis)
else:
output = output / np.sum(output, axis, keepdims=True)
output = np.clip(output, backend.epsilon(), 1.0 - backend.epsilon())
log_prob = np.log(output)
target = one_hot(target, output.shape[axis], axis=axis)
return -np.sum(target * log_prob, axis=axis)
def binary_crossentropy(target, output, from_logits=False):
target = np.array(target)
output = np.array(output)
View on GitHub (pinned to 7a34a03db6)