{"record":{"id":"8c69bcfc4a73c382","repo":"WZMIAOMIAO/deep-learning-for-image-processing","slug":"expected-target-boxes-to-be-of-type-tensor-got","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/faster_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\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],","sourceCodeStart":54,"sourceCodeEnd":90,"githubUrl":"https://github.com/WZMIAOMIAO/deep-learning-for-image-processing/blob/1ec3fe6f374fc9969973a61f819de25658595afa/pytorch_object_detection/faster_rcnn/network_files/faster_rcnn_framework.py#L54-L90","documentation":"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.","triggerScenarios":"Building targets with boxes as list-of-lists, numpy arrays, or PIL/other types and passing them straight into model(images, targets) during training.","commonSituations":"Reading annotations from XML/JSON without converting to tensors, using torchvision transforms that return numpy, or mixing a dataset written for a different framework.","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)."],"exampleFix":"# before\ntarget = {'boxes': [[10, 20, 110, 120]], 'labels': [1]}\n# after\nimport torch\ntarget = {'boxes': torch.as_tensor([[10, 20, 110, 120]], dtype=torch.float32),\n          'labels': torch.as_tensor([1], dtype=torch.int64)}","handlingStrategy":"type-guard","validationCode":"for t in targets:\n    assert isinstance(t['boxes'], torch.Tensor), f\"boxes must be Tensor, got {type(t['boxes'])}\"","typeGuard":"def is_tensor_boxes(target: dict) -> bool:\n    return isinstance(target.get('boxes'), torch.Tensor)","tryCatchPattern":"try:\n    loss_dict = model(images, targets)\nexcept ValueError as e:\n    if 'of type Tensor' in str(e):\n        targets = [{'boxes': torch.as_tensor(t['boxes'], dtype=torch.float32), 'labels': torch.as_tensor(t['labels'], dtype=torch.int64)} for t in targets]\n        loss_dict = model(images, targets)\n    else:\n        raise","preventionTips":["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"],"tags":["training","targets","type-error","tensor"],"backgroundTag":"box-shape-validation-failed","analyzedSha":"1ec3fe6f374fc9969973a61f819de25658595afa","analyzedAt":"2026-08-30T09:19:11.901Z","schemaVersion":2},"datasetVersion":"2026-08-30T13:17:10.514Z"}