{"record":{"id":"42ea9c8057eaba24","repo":"WZMIAOMIAO/deep-learning-for-image-processing","slug":"expected-target-boxes-to-be-of-type-tensor-got-42ea9c","errorCode":null,"errorMessage":"Expected target boxes to be of type Tensor, got {:}.","messagePattern":"Expected target boxes to be of type Tensor, got (.+?)\\.","errorType":"validation","errorClass":"ValueError","httpStatus":null,"severity":"error","filePath":"pytorch_object_detection/mask_rcnn/network_files/faster_rcnn_framework.py","lineNumber":72,"sourceCode":"                During training, it returns a dict[Tensor] which contains the losses.\n                During testing, it returns list[BoxList] contains additional fields\n                like `scores`, `labels` and `mask` (for Mask R-CNN models).\n\n        \"\"\"\n        if self.training and targets is None:\n            raise ValueError(\"In training mode, targets should be passed\")\n\n        if self.training:\n            assert targets is not None\n            for target in targets:         # 进一步判断传入的target的boxes参数是否符合规定\n                boxes = target[\"boxes\"]\n                if isinstance(boxes, torch.Tensor):\n                    if len(boxes.shape) != 2 or boxes.shape[-1] != 4:\n                        raise ValueError(\"Expected target boxes to be a tensor\"\n                                         \"of shape [N, 4], got {:}.\".format(\n                                          boxes.shape))\n                else:\n                    raise ValueError(\"Expected target boxes to be of type \"\n                                     \"Tensor, got {:}.\".format(type(boxes)))\n\n        original_image_sizes = torch.jit.annotate(List[Tuple[int, int]], [])\n        for img in images:\n            val = img.shape[-2:]\n            assert len(val) == 2  # 防止输入的是个一维向量\n            original_image_sizes.append((val[0], val[1]))\n        # original_image_sizes = [img.shape[-2:] for img in images]\n\n        images, targets = self.transform(images, targets)  # 对图像进行预处理\n        # print(images.tensors.shape)\n        features = self.backbone(images.tensors)  # 将图像输入backbone得到特征图\n        if isinstance(features, torch.Tensor):  # 若只在一层特征层上预测，将feature放入有序字典中，并编号为‘0’\n            features = OrderedDict([('0', features)])  # 若在多层特征层上预测，传入的就是一个有序字典\n\n        # 将特征层以及标注target信息传入rpn中\n        # proposals: List[Tensor], Tensor_shape: [num_proposals, 4],\n        # 每个proposals是绝对坐标，且为(x1, y1, x2, y2)格式","sourceCodeStart":54,"sourceCodeEnd":90,"githubUrl":"https://github.com/WZMIAOMIAO/deep-learning-for-image-processing/blob/1ec3fe6f374fc9969973a61f819de25658595afa/pytorch_object_detection/mask_rcnn/network_files/faster_rcnn_framework.py#L54-L90","documentation":"forward checks that each target['boxes'] is a torch.Tensor during training. If boxes is any other type (list, numpy array, tuple), it raises this ValueError including the actual Python type. The model needs tensor ops on boxes, so non-tensor inputs are rejected.","triggerScenarios":"Building targets from a dataset that returns boxes as lists of lists or numpy arrays and never converting to torch.Tensor before model(images, targets).","commonSituations":"Custom datasets/collate functions omitting torch.as_tensor conversion; JSON-loaded annotations passed directly; mixing torchvision versions where some converters are no longer applied.","solutions":["Convert boxes with torch.as_tensor(boxes, dtype=torch.float32) when building each target dict","Fix the dataset/collate_fn to always emit tensors for 'boxes' and 'labels'","Add a per-batch assert isinstance(t['boxes'], torch.Tensor) to catch bad samples early"],"exampleFix":"// before\ntarget = {'boxes': [[10, 20, 110, 120]], 'labels': [1]}\n// after\ntarget = {'boxes': torch.as_tensor([[10, 20, 110, 120]], dtype=torch.float32), 'labels': torch.as_tensor([1], dtype=torch.int64)}","handlingStrategy":"type-guard","validationCode":"for t in targets:\n    if not isinstance(t['boxes'], torch.Tensor):\n        t['boxes'] = torch.as_tensor(t['boxes'], dtype=torch.float32)","typeGuard":"def is_tensor_boxes(t):\n    return isinstance(t.get('boxes'), torch.Tensor)","tryCatchPattern":"try:\n    losses = model(images, targets)\nexcept ValueError as e:\n    if 'of type Tensor' in str(e):\n        targets = [{**t, 'boxes': torch.as_tensor(t['boxes'], dtype=torch.float32)} for t in targets]\n        losses = model(images, targets)\n    else:\n        raise","preventionTips":["Convert all annotations to torch.Tensor in __getitem__, not in the training loop","Use a typed Target dataclass that coerces boxes/labels to tensors","Keep collate_fn responsible for tensor conversion"],"tags":["pytorch","validation","types"],"backgroundTag":"wrong-argument-type","analyzedSha":"1ec3fe6f374fc9969973a61f819de25658595afa","analyzedAt":"2026-08-30T09:19:11.901Z","schemaVersion":2},"datasetVersion":"2026-08-30T13:17:10.514Z"}