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 target validation in FasterRCNN.forward, if target['boxes'] is a torch.Tensor it must be 2-D with last dimension 4 ([N,4] xyxy boxes); otherwise this ValueError is raised with the actual shape. It enforces the box tensor contract before boxes flow into the RPN/ROI heads.
Source
Thrown at pytorch_object_detection/faster_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’View on GitHub (pinned to 1ec3fe6f37)
Solutions
- Reshape boxes to [N,4]: boxes = boxes.view(-1, 4) or torch.as_tensor(boxes).reshape(-1, 4).
- For a single box, wrap it: boxes = boxes.unsqueeze(0).
- Keep labels in target['labels'], not inside target['boxes'].
- Verify each target before training: check boxes.ndim == 2 and boxes.shape[1] == 4.
- Print boxes.shape for the offending target to see the actual layout.
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: type-guard
Validate before calling
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 if hasattr(b,'shape') else b}" Type guard
def is_valid_box_tensor(b) -> bool:
return isinstance(b, torch.Tensor) and b.ndim == 2 and b.shape[-1] == 4 Try / catch
try:
loss_dict = model(images, targets)
except ValueError as e:
if 'shape [N, 4]' in str(e):
targets = [{'boxes': t['boxes'].view(-1, 4), 'labels': t['labels']} for t in targets]
loss_dict = model(images, targets)
else:
raise Prevention
- Always store boxes as float32 tensors of shape [N,4] in the dataset
- Use torch.as_tensor(boxes).reshape(-1, 4) when building targets
- Keep labels separate from boxes
- Add an assert in collate_fn validating every target
When it happens
Trigger: Passing boxes with wrong shape — e.g. shape [N] (flattened), [4] (single box unbatched), [N,5] (with extra column), or a list of per-coordinate values stored as a tensor of wrong rank — in training targets.
Common situations: Custom datasets building targets incorrectly, forgetting torch.stack/torch.as_tensor around per-box rows, concatenating labels into the boxes tensor, or loading boxes as normalized [0,1] values in a different layout.
Related errors
- Expected target boxes to be of type Tensor, got {:}.
- In training mode, targets should be passed
- images is expected to be a list of 3d tensors of shape [C, H
- 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/13e44162c17ae5bc.
Report an issue: GitHub.