keras-team/keras · error · ValueError
Expected `bounding_boxes['boxes']` to have rank 2 or 3, with
Error message
Expected `bounding_boxes['boxes']` to have rank 2 or 3, with shape (num_boxes, 4) or (batch_size, num_boxes, 4). Received: bounding_boxes['boxes'].shape={boxes_shape} What it means
validate_bounding_boxes only accepts dense 'boxes' of rank 2 ((num_boxes, 4), unbatched) or rank 3 ((batch, num_boxes, 4), batched). Rank-1, rank-4, or higher boxes tensors cannot be interpreted as a set of xyxy boxes and are rejected.
Source
Thrown at keras/src/layers/preprocessing/image_preprocessing/bounding_boxes/validation.py:176
if len(labels_shape) not in {1, 2}:
raise ValueError(
"Found "
f"bounding_boxes['boxes'].shape={boxes_shape} "
"and expected bounding_boxes['labels'] to have "
"rank 1 or 2, but received: "
f"bounding_boxes['labels'].shape={labels_shape} "
)
elif len(boxes_shape) == 3:
if len(labels_shape) not in {2, 3}:
raise ValueError(
"Found "
f"bounding_boxes['boxes'].shape={boxes_shape} "
"and expected bounding_boxes['labels'] to have "
"rank 2 or 3, but received: "
f"bounding_boxes['labels'].shape={labels_shape} "
)
else:
raise ValueError(
"Expected `bounding_boxes['boxes']` "
"to have rank 2 or 3, with shape "
"(num_boxes, 4) or (batch_size, num_boxes, 4). "
"Received: "
f"bounding_boxes['boxes'].shape={boxes_shape}"
)
View on GitHub (pinned to 7a34a03db6)
Solutions
- Squeeze stray leading dims: boxes = keras.ops.squeeze(boxes, axis=0) until rank is 2 or 3
- For a single image ensure shape (num_boxes, 4); for a batch (batch, num_boxes, 4)
- Print boxes.shape right before the call to spot the extra axis
Example fix
# before boxes = np.array([all_boxes]) # shape (1, batch, boxes, 4) -> rank 4 # after boxes = np.array(all_boxes) # shape (batch, boxes, 4)
Defensive patterns
Strategy: validation
Validate before calling
assert len(bbs['boxes'].shape) in (2, 3), bbs['boxes'].shape
Prevention
- Squeeze singleton leading dims before packing boxes
- Verify last dim is 4 (xyxy) when constructing the tensor
When it happens
Trigger: densify_bounding_boxes with boxes of rank 1 (flat 8-vector), rank 4 (extra leading dims, e.g. (1, batch, boxes, 4)).
Common situations: Residual batch dim of 1 left after expand_dims; wrapping once more in np.array([x]) making rank 4; feeding keypoint arrays of the wrong rank.
Related errors
- Found bounding_boxes['boxes'].shape={boxes_shape} and expect
- If `bounding_boxes['boxes']` is a list, then `bounding_boxes
- Found bounding_boxes['boxes'].shape={boxes_shape} and expect
- Expected as input a list/tuple of 2 tensors. Received input_
- `height` and `width` must be set if `format='xyxy'`.
AI-assisted analysis of keras-team/keras@7a34a03db6 (2026-08-25).
Data as JSON: /api/errors/9f23f506da0a44a8.
Report an issue: GitHub.