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
The else-branch of the same validation: if target['boxes'] is not a torch.Tensor (e.g. a Python list, numpy array, or tuple), forward raises this ValueError naming the actual type. The training path requires boxes as tensors so they can participate in autograd and IoU computations on device.
Source
Thrown at pytorch_object_detection/faster_rcnn/network_files/faster_rcnn_framework.py:72
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)]) # 若在多层特征层上预测,传入的就是一个有序字典
# 将特征层以及标注target信息传入rpn中
# proposals: List[Tensor], Tensor_shape: [num_proposals, 4],View on GitHub (pinned to 1ec3fe6f37)
Solutions
- Convert to tensor: boxes = torch.as_tensor(boxes, dtype=torch.float32).
- Do the conversion inside the dataset __getitem__ so targets are always tensors.
- Also move tensors to the model device (cuda) before the forward call.
- Validate types before the loop: isinstance(target['boxes'], torch.Tensor).
Example fix
# before
target = {'boxes': [[10, 20, 110, 120]], 'labels': [1]}
# after
import torch
target = {'boxes': torch.as_tensor([[10, 20, 110, 120]], dtype=torch.float32),
'labels': torch.as_tensor([1], dtype=torch.int64)} Defensive patterns
Strategy: type-guard
Validate before calling
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:
return isinstance(target.get('boxes'), torch.Tensor) Try / catch
try:
loss_dict = model(images, targets)
except ValueError as e:
if 'of type Tensor' in str(e):
targets = [{'boxes': torch.as_tensor(t['boxes'], dtype=torch.float32), 'labels': torch.as_tensor(t['labels'], dtype=torch.int64)} for t in targets]
loss_dict = model(images, targets)
else:
raise Prevention
- Convert boxes to torch.as_tensor(..., dtype=torch.float32) inside __getitem__
- Also move targets to the training device before forward
- Don't pass numpy lists/arrays as targets
- Validate target types in a unit test for the dataset
When it happens
Trigger: Building targets with boxes as list-of-lists, numpy arrays, or PIL/other types and passing them straight into model(images, targets) during training.
Common situations: Reading annotations from XML/JSON without converting to tensors, using torchvision transforms that return numpy, or mixing a dataset written for a different framework.
Related errors
- Expected target boxes to be a tensorof shape [N, 4], got {:}
- In training mode, targets should be passed
- sampler should be an instance of torch.utils.data.Sampler, b
- No ground-truth boxes available for one of the images during
- No proposal boxes available for one of the images during tra
AI-assisted analysis of WZMIAOMIAO/deep-learning-for-image-processing@1ec3fe6f37 (2026-08-30).
Data as JSON: /api/errors/8c69bcfc4a73c382.
Report an issue: GitHub.