{"record":{"id":"eeef6e091ea3028b","repo":"WZMIAOMIAO/deep-learning-for-image-processing","slug":"expected-target-boxes-to-be-of-type-tensor-got-eeef6e","errorCode":null,"errorMessage":"Expected target boxes to be of type Tensor, got {:}.","messagePattern":"Expected target boxes to be of type Tensor, got (.+?)\\.","errorType":"exception","errorClass":"ValueError","httpStatus":null,"severity":"error","filePath":"pytorch_object_detection/retinaNet/network_files/retinanet.py","lineNumber":467,"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            # check targets info\n            for target in targets:\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(boxes.shape))\n                else:\n                    raise ValueError(\"Expected target boxes to be of type \"\n                                     \"Tensor, got {:}.\".format(type(boxes)))\n\n        # get the original images sizes\n        original_img_sizes: List[Tuple[int, int]] = []\n        for img in images:\n            val = img.shape[-2:]\n            assert len(val) == 2\n            original_img_sizes.append((val[0], val[1]))  # h, w\n\n        # transform the input\n        images, targets = self.transform(images, targets)\n\n        # Check for degenerate boxes\n        # TODO: Move this to a function\n        if targets is not None:\n            for target_idx, target in enumerate(targets):\n                boxes = target[\"boxes\"]\n                degenerate_boxes = boxes[:, 2:] <= boxes[:, :2]","sourceCodeStart":449,"sourceCodeEnd":485,"githubUrl":"https://github.com/WZMIAOMIAO/deep-learning-for-image-processing/blob/1ec3fe6f374fc9969973a61f819de25658595afa/pytorch_object_detection/retinaNet/network_files/retinanet.py#L449-L485","documentation":"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'>).","triggerScenarios":"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.","commonSituations":"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.","solutions":["Convert in the Dataset: boxes = torch.as_tensor(boxes, dtype=torch.float32).","Convert at call time: targets = [{**t, 'boxes': torch.as_tensor(t['boxes'])} for t in targets].","Check labels key too — apply the same tensor conversion to 'labels' and 'iscrowd'.","Standardize the Dataset output contract so targets are always tensors of float32/ int64."],"exampleFix":"// before\ntarget = {\"boxes\": np.array([[10., 20., 100., 120.]]), \"labels\": [1]}\n// after\ntarget = {\"boxes\": torch.as_tensor([[10., 20., 100., 120.]], dtype=torch.float32),\n          \"labels\": torch.as_tensor([1], dtype=torch.int64)}","handlingStrategy":"type-guard","validationCode":"import torch\nfor 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    import torch\n    return isinstance(target.get(\"boxes\"), torch.Tensor)","tryCatchPattern":"try:\n    outputs = 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        outputs = model(images, targets)\n    else:\n        raise","preventionTips":["Convert all annotations with torch.as_tensor inside Dataset.__getitem__.","Convert labels and iscrowd keys the same way for consistency.","Pin the Dataset output contract in a unit test.","Avoid passing numpy arrays/lists straight from JSON loaders."],"tags":["pytorch","object-detection","type-error","validation"],"backgroundTag":"wrong-argument-type","analyzedSha":"1ec3fe6f374fc9969973a61f819de25658595afa","analyzedAt":"2026-08-30T09:19:11.901Z","schemaVersion":2},"datasetVersion":"2026-08-30T13:17:10.514Z"}