{"record":{"id":"43dcc24666f4c4b5","repo":"WZMIAOMIAO/deep-learning-for-image-processing","slug":"target-should-not-be-none","errorCode":null,"errorMessage":"target should not be None.","messagePattern":"target should not be None\\.","errorType":"exception","errorClass":"ValueError","httpStatus":null,"severity":"critical","filePath":"pytorch_object_detection/mask_rcnn/network_files/roi_head.py","lineNumber":322,"sourceCode":"                                proposals,  # type: List[Tensor]\n                                targets     # type: Optional[List[Dict[str, Tensor]]]\n                                ):\n        # type: (...) -> Tuple[List[Tensor], List[Tensor], List[Tensor], List[Tensor]]\n        \"\"\"\n        划分正负样本，统计对应gt的标签以及边界框回归信息\n        list元素个数为batch_size\n        Args:\n            proposals: rpn预测的boxes\n            targets:\n\n        Returns:\n\n        \"\"\"\n\n        # 检查target数据是否为空\n        self.check_targets(targets)\n        if targets is None:\n            raise ValueError(\"target should not be None.\")\n\n        dtype = proposals[0].dtype\n        device = proposals[0].device\n\n        # 获取标注好的boxes以及labels信息\n        gt_boxes = [t[\"boxes\"].to(dtype) for t in targets]\n        gt_labels = [t[\"labels\"] for t in targets]\n\n        # append ground-truth bboxes to proposal\n        # 将gt_boxes拼接到proposal后面\n        proposals = self.add_gt_proposals(proposals, gt_boxes)\n\n        # get matching gt indices for each proposal\n        # 为每个proposal匹配对应的gt_box，并划分到正负样本中\n        matched_idxs, labels = self.assign_targets_to_proposals(proposals, gt_boxes, gt_labels)\n        # sample a fixed proportion of positive-negative proposals\n        # 按给定数量和比例采样正负样本\n        sampled_inds = self.subsample(labels)","sourceCodeStart":304,"sourceCodeEnd":340,"githubUrl":"https://github.com/WZMIAOMIAO/deep-learning-for-image-processing/blob/1ec3fe6f374fc9969973a61f819de25658595afa/pytorch_object_detection/mask_rcnn/network_files/roi_head.py#L304-L340","documentation":"During training, ROIHeads.select_training_samples needs ground-truth targets to match proposals against and compute classification/box losses. The code checks targets via check_targets first, then raises ValueError if the targets argument itself is None, since training cannot proceed without annotations.","triggerScenarios":"Calling model(images) in train() mode (model.train()) without passing targets, e.g. model(images) instead of model(images, targets).","commonSituations":"Forgetting to pass targets in the training loop; a dataloader returning None targets for unlabeled samples; reusing inference code for training.","solutions":["Pass a non-None list of target dicts (with 'boxes' and 'labels') in training mode","Verify the dataloader actually yields targets and filters out empty samples","Only omit targets during inference under torch.no_grad() with model.eval()"],"exampleFix":"// before\nloss_dict = model(images)\n// after\nloss_dict = model(images, targets)  # targets = [{'boxes': ..., 'labels': ..., 'masks': ...}]","handlingStrategy":"validation","validationCode":"if model.training:\n    assert targets is not None and all('boxes' in t and 'labels' in t for t in targets), \"targets required in train mode\"\n    losses = model(images, targets)","typeGuard":"def has_valid_targets(targets):\n    return targets is not None and isinstance(targets, list) and all(isinstance(t, dict) and 'boxes' in t for t in targets)","tryCatchPattern":"try:\n    losses = model(images, targets)\nexcept ValueError as e:\n    if 'target' in str(e): targets = load_targets(batch)\n    raise","preventionTips":["Never call a detection model in train() mode without targets","Filter out unlabeled samples in the dataset __getitem__","Use model.eval() for inference-only paths"],"tags":["python","mask-rcnn","training"],"backgroundTag":"missing-required-argument","analyzedSha":"1ec3fe6f374fc9969973a61f819de25658595afa","analyzedAt":"2026-08-30T09:19:11.901Z","schemaVersion":2},"datasetVersion":"2026-08-30T13:17:10.514Z"}