WZMIAOMIAO/deep-learning-for-image-processing · error · ValueError

Expected target boxes to be a tensorof shape [N, 4], got {:}

Error message

Expected target boxes to be a tensorof shape [N, 4], got {:}.

What it means

RetinaNet.forward validates that each target['boxes'] is a torch.Tensor with shape [N, 4]. When it is a tensor but has wrong rank or last dimension (not 4 coordinates), the shape-check raises ValueError including the actual shape. The typo 'tensorof' is in the original message string.

Source

Thrown at pytorch_object_detection/retinaNet/network_files/retinanet.py:464

        Returns:
            result (list[BoxList] or dict[Tensor]): the output from the model.
                During training, it returns a dict[Tensor] which contains the losses.
                During testing, it returns list[BoxList] contains additional fields
                like `scores`, `labels` and `mask` (for Mask R-CNN models).

        """
        if self.training and targets is None:
            raise ValueError("In training mode, targets should be passed")

        if self.training:
            assert targets is not None
            # check targets info
            for target in targets:
                boxes = target["boxes"]
                if isinstance(boxes, torch.Tensor):
                    if len(boxes.shape) != 2 or boxes.shape[-1] != 4:
                        raise ValueError("Expected target boxes to be a tensor"
                                         "of shape [N, 4], got {:}.".format(boxes.shape))
                else:
                    raise ValueError("Expected target boxes to be of type "
                                     "Tensor, got {:}.".format(type(boxes)))

        # get the original images sizes
        original_img_sizes: List[Tuple[int, int]] = []
        for img in images:
            val = img.shape[-2:]
            assert len(val) == 2
            original_img_sizes.append((val[0], val[1]))  # h, w

        # transform the input
        images, targets = self.transform(images, targets)

        # Check for degenerate boxes
        # TODO: Move this to a function
        if targets is not None:

View on GitHub (pinned to 1ec3fe6f37)

Solutions

  1. Reshape to 2-D: boxes.view(-1, 4) or boxes.unsqueeze(0) for a single box.
  2. In your Dataset, return boxes as a [num_objects, 4] tensor (x1, y1, x2, y2 per row).
  3. Fix the collate/stacking logic so per-image targets stay individual dicts, not batched tensors.
  4. Add a pre-forward assert: all(t['boxes'].ndim == 2 and t['boxes'].shape[-1] == 4 ...).

Example fix

// before
target = {"boxes": torch.tensor([10., 20., 100., 120.])}  # shape [4]
// after
target = {"boxes": torch.tensor([[10., 20., 100., 120.]])}  # shape [1, 4]
Defensive patterns

Strategy: type-guard

Validate before calling

import torch
for t in targets:
    b = t["boxes"]
    assert isinstance(b, torch.Tensor) and b.ndim == 2 and b.shape[-1] == 4, f"bad boxes shape {b.shape}"

Type guard

def is_valid_boxes_tensor(boxes) -> bool:
    import torch
    return isinstance(boxes, torch.Tensor) and boxes.ndim == 2 and boxes.shape[-1] == 4

Try / catch

try:
    outputs = model(images, targets)
except ValueError as e:
    if "of shape [N, 4]" in str(e):
        targets = [{**t, "boxes": torch.as_tensor(t["boxes"]).view(-1, 4)} for t in targets]
        outputs = model(images, targets)
    else:
        raise

Prevention

When it happens

Trigger: Passing boxes shaped [N] (flat 4*N), [4] (single box, 1-D), [N, 4, 1] or [B, N, 4] (batched); constructing targets from numpy arrays converted with wrong reshape; collate functions stacking boxes into 3-D tensors.

Common situations: Custom Dataset returning a single box tensor [4] instead of [1, 4]; concatenating per-image boxes during batching; migrating code from older detection repos with different target layouts; accidental torch.stack of box lists.

Understand the failure class

Background: Tensor shape mismatch errors ("must have shape", "expected shape ... got ..."): when tensor dimensions disagree with what an op or layer was told to expect — this error's family across 6 libraries.

Related errors


AI-assisted analysis of WZMIAOMIAO/deep-learning-for-image-processing@1ec3fe6f37 (2026-08-30). Data as JSON: /api/errors/48b84c586624cbe0. Report an issue: GitHub.