{"record":{"id":"0437ef70be36078a","repo":"WZMIAOMIAO/deep-learning-for-image-processing","slug":"num-classes-should-be-none-when-box-predictor-is-s-0437ef","errorCode":null,"errorMessage":"num_classes should be None when box_predictor is specified","messagePattern":"num_classes should be None when box_predictor is specified","errorType":"validation","errorClass":"ValueError","httpStatus":null,"severity":"error","filePath":"pytorch_object_detection/mask_rcnn/network_files/faster_rcnn_framework.py","lineNumber":277,"sourceCode":"                 box_roi_pool=None, box_head=None, box_predictor=None,\n                 # 移除低目标概率      fast rcnn中进行nms处理的阈值   对预测结果根据score排序取前100个目标\n                 box_score_thresh=0.05, box_nms_thresh=0.5, box_detections_per_img=100,\n                 box_fg_iou_thresh=0.5, box_bg_iou_thresh=0.5,   # fast rcnn计算误差时，采集正负样本设置的阈值\n                 box_batch_size_per_image=512, box_positive_fraction=0.25,  # fast rcnn计算误差时采样的样本数，以及正样本占所有样本的比例\n                 bbox_reg_weights=None):\n        if not hasattr(backbone, \"out_channels\"):\n            raise ValueError(\n                \"backbone should contain an attribute out_channels\"\n                \"specifying the number of output channels  (assumed to be the\"\n                \"same for all the levels\"\n            )\n\n        # assert isinstance(rpn_anchor_generator, (AnchorsGenerator, type(None)))\n        assert isinstance(box_roi_pool, (MultiScaleRoIAlign, type(None)))\n\n        if num_classes is not None:\n            if box_predictor is not None:\n                raise ValueError(\"num_classes should be None when box_predictor \"\n                                 \"is specified\")\n        else:\n            if box_predictor is None:\n                raise ValueError(\"num_classes should not be None when box_predictor \"\n                                 \"is not specified\")\n\n        # 预测特征层的channels\n        out_channels = backbone.out_channels\n\n        # 若anchor生成器为空，则自动生成针对resnet50_fpn的anchor生成器\n        if rpn_anchor_generator is None:\n            anchor_sizes = ((32,), (64,), (128,), (256,), (512,))\n            aspect_ratios = ((0.5, 1.0, 2.0),) * len(anchor_sizes)\n            rpn_anchor_generator = AnchorsGenerator(\n                anchor_sizes, aspect_ratios\n            )\n\n        # 生成RPN通过滑动窗口预测网络部分","sourceCodeStart":259,"sourceCodeEnd":295,"githubUrl":"https://github.com/WZMIAOMIAO/deep-learning-for-image-processing/blob/1ec3fe6f374fc9969973a61f819de25658595afa/pytorch_object_detection/mask_rcnn/network_files/faster_rcnn_framework.py#L259-L295","documentation":"The constructor enforces mutual exclusivity: if num_classes is given AND a prebuilt box_predictor is supplied, the class count is ambiguous (the predictor already encodes its own output size), so it raises this ValueError.","triggerScenarios":"Calling fasterrcnn_resnet50_fpn(pretrained=True, num_classes=..., box_predictor=FastRCNNPredictor(...)) or FasterRCNN(..., num_classes=91, box_predictor=my_predictor) — i.e. specifying both at once.","commonSituations":"Fine-tuning tutorials where users replace box_predictor but forget to drop num_classes; copy-pasting constructor args from two different customization recipes.","solutions":["When supplying a custom box_predictor, pass num_classes=None","When you want the library to build the predictor, pass box_predictor=None and only num_classes","Replace the predictor after construction instead: build the model with num_classes, then swap model.roi_heads.box_predictor"],"exampleFix":"// before\nmodel = fasterrcnn_resnet50_fpn(pretrained=True, num_classes=5,\n                               box_predictor=FastRCNNPredictor(1024, 5))\n// after\nmodel = fasterrcnn_resnet50_fpn(pretrained=True, box_predictor=FastRCNNPredictor(1024, 5))  # num_classes omitted/None","handlingStrategy":"validation","validationCode":"assert not (num_classes is not None and box_predictor is not None), 'pass either num_classes or box_predictor, not both'","typeGuard":null,"tryCatchPattern":"try:\n    model = FasterRCNN(backbone, num_classes=num_classes, box_predictor=box_predictor)\nexcept ValueError as e:\n    if 'should be None when box_predictor' in str(e):\n        model = FasterRCNN(backbone, box_predictor=box_predictor)\n    else:\n        raise","preventionTips":["Pick one customization recipe: either num_classes OR a prebuilt predictor","When swapping predictors post-construction, never also pass num_classes","Review constructor kwargs before commit; both keys together is always a bug"],"tags":["pytorch","config","api-misuse"],"backgroundTag":"conflicting-arguments","analyzedSha":"1ec3fe6f374fc9969973a61f819de25658595afa","analyzedAt":"2026-08-30T09:19:11.901Z","schemaVersion":2},"datasetVersion":"2026-08-30T13:17:10.514Z"}