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

During training forward validates each target['boxes']: it must be a 2-D tensor whose last dimension is 4 (xyxy boxes for N objects). A tensor with wrong rank or last-dim size raises this ValueError with the offending shape.

Source

Thrown at pytorch_object_detection/mask_rcnn/network_files/faster_rcnn_framework.py:68

            targets (list[Dict[Tensor]]): ground-truth boxes present in the image (optional)

        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
            for target in targets:         # 进一步判断传入的target的boxes参数是否符合规定
                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)))

        original_image_sizes = torch.jit.annotate(List[Tuple[int, int]], [])
        for img in images:
            val = img.shape[-2:]
            assert len(val) == 2  # 防止输入的是个一维向量
            original_image_sizes.append((val[0], val[1]))
        # original_image_sizes = [img.shape[-2:] for img in images]

        images, targets = self.transform(images, targets)  # 对图像进行预处理
        # print(images.tensors.shape)
        features = self.backbone(images.tensors)  # 将图像输入backbone得到特征图
        if isinstance(features, torch.Tensor):  # 若只在一层特征层上预测,将feature放入有序字典中,并编号为‘0’
            features = OrderedDict([('0', features)])  # 若在多层特征层上预测,传入的就是一个有序字典

View on GitHub (pinned to 1ec3fe6f37)

Solutions

  1. Ensure every target['boxes'] is a FloatTensor of shape [N, 4] in (xmin, ymin, xmax, ymax) format
  2. Reshape single boxes with .reshape(1, 4) or .unsqueeze(0)
  3. Inspect target shapes right before forward (print/assert boxes.shape) to find the offending sample

Example fix

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

Strategy: validation

Validate before calling

for t in targets:
    b = t['boxes']
    assert isinstance(b, torch.Tensor) and b.dim() == 2 and b.shape[-1] == 4, f'bad boxes shape {tuple(b.shape) if hasattr(b,"shape") else type(b)}'

Type guard

def is_valid_boxes(boxes):
    return isinstance(boxes, torch.Tensor) and boxes.dim() == 2 and boxes.shape[-1] == 4

Try / catch

try:
    losses = model(images, targets)
except ValueError as e:
    if 'shape [N, 4]' in str(e):
        for i, t in enumerate(targets):
            print(i, type(t['boxes']), getattr(t['boxes'], 'shape', None))
    raise

Prevention

When it happens

Trigger: Passing boxes with shape [4] (single box, not batched), [N, 5] (extra column like score/area), an empty tensor of wrong rank, or boxes built with the wrong coordinate format/layout in a training batch.

Common situations: Dataset collation that forgets to stack boxes into [N,4]; label converters appending extra fields; copying torchvision's newer targets validation expectations into older-style data pipelines; numpy arrays accidentally kept as lists inside targets.

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/159ee81d219c4207. Report an issue: GitHub.