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

Expected target boxes to be of type Tensor, got {:}.

Error message

Expected target boxes to be of type Tensor, got {:}.

What it means

RetinaNet.forward requires target['boxes'] to be a torch.Tensor specifically. If it is a list, numpy array, or other sequence, the type check raises ValueError with the actual Python type (e.g. <class 'numpy.ndarray'> or <class 'list'>).

Source

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

                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:
            for target_idx, target in enumerate(targets):
                boxes = target["boxes"]
                degenerate_boxes = boxes[:, 2:] <= boxes[:, :2]

View on GitHub (pinned to 1ec3fe6f37)

Solutions

  1. Convert in the Dataset: boxes = torch.as_tensor(boxes, dtype=torch.float32).
  2. Convert at call time: targets = [{**t, 'boxes': torch.as_tensor(t['boxes'])} for t in targets].
  3. Check labels key too — apply the same tensor conversion to 'labels' and 'iscrowd'.
  4. Standardize the Dataset output contract so targets are always tensors of float32/ int64.

Example fix

// before
target = {"boxes": np.array([[10., 20., 100., 120.]]), "labels": [1]}
// after
target = {"boxes": torch.as_tensor([[10., 20., 100., 120.]], dtype=torch.float32),
          "labels": torch.as_tensor([1], dtype=torch.int64)}
Defensive patterns

Strategy: type-guard

Validate before calling

import torch
for t in targets:
    assert isinstance(t["boxes"], torch.Tensor), f"boxes must be Tensor, got {type(t['boxes'])}"

Type guard

def is_tensor_boxes(target: dict) -> bool:
    import torch
    return isinstance(target.get("boxes"), torch.Tensor)

Try / catch

try:
    outputs = model(images, targets)
except ValueError as e:
    if "of type Tensor" in str(e):
        targets = [{**t, "boxes": torch.as_tensor(t["boxes"], dtype=torch.float32)} for t in targets]
        outputs = model(images, targets)
    else:
        raise

Prevention

When it happens

Trigger: Dataset __getitem__ returns boxes as list-of-lists or np.array without torch.as_tensor conversion; targets loaded straight from JSON/pickle; passing VOC XML-parsed coordinates without tensor conversion.

Common situations: Datasets converted from COCO json where boxes remain numpy; users building targets manually in notebooks; mixing torchvision versions where older examples passed lists; code migrated from numpy-only pipelines.

Understand the failure class

Background: "Wrong argument type", "must be a string", "expected Array or Prism::Scope": TypeError and ArgumentError when a library receives a value of the wrong type — this error's family across 28 libraries.

Related errors


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