{"record":{"id":"b897d1da54dfd312","repo":"WZMIAOMIAO/deep-learning-for-image-processing","slug":"num-classes-should-be-none-when-box-predictor-is-s","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/faster_rcnn/network_files/faster_rcnn_framework.py","lineNumber":278,"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":260,"sourceCodeEnd":296,"githubUrl":"https://github.com/WZMIAOMIAO/deep-learning-for-image-processing/blob/1ec3fe6f374fc9969973a61f819de25658595afa/pytorch_object_detection/faster_rcnn/network_files/faster_rcnn_framework.py#L260-L296","documentation":"The constructor enforces mutual exclusivity: if num_classes is provided AND a pre-built box_predictor is supplied, it raises 'num_classes should be None when box_predictor is specified' because the predictor already encodes the class count and num_classes would be ambiguous. The complementary branch raises if neither combination is coherent (num_classes None and box_predictor None).","triggerScenarios":"Calling fasterrcnn(backbone=..., num_classes=91, box_predictor=my_predictor) — passing both a custom FastRCNNPredictor and num_classes at once.","commonSituations":"Fine-tuning workflows where users load a pretrained model, swap in a custom box_predictor for their dataset, but forget to drop num_classes from the constructor call; or copy-pasting both a predictor constructor and a num_classes argument.","solutions":["When supplying box_predictor, pass num_classes=None.","When you want the framework to build the predictor, pass num_classes and leave box_predictor=None.","Standard fine-tune pattern: build model with num_classes, then replace model.roi_heads.box_predictor with your custom predictor afterwards.","Check the constructor call for leftover arguments after switching approaches."],"exampleFix":"# before\npredictor = FastRCNNPredictor(in_features, num_classes=5)\nmodel = fasterrcnn(backbone=backbone, num_classes=5, box_predictor=predictor)\n# after\npredictor = FastRCNNPredictor(in_features, num_classes=5)\nmodel = fasterrcnn(backbone=backbone, box_predictor=predictor)  # 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":"def predictor_args_ok(num_classes, box_predictor) -> bool:\n    return (num_classes is None) == (box_predictor is None)","tryCatchPattern":"try:\n    model = fasterrcnn(backbone=backbone, num_classes=num_classes, box_predictor=box_predictor)\nexcept ValueError as e:\n    if 'num_classes should be None' in str(e):\n        model = fasterrcnn(backbone=backbone, box_predictor=box_predictor)\n    else:\n        raise","preventionTips":["Pass num_classes XOR box_predictor, never both","For fine-tuning, build with num_classes then swap model.roi_heads.box_predictor afterwards","Read the constructor signature before combining pretrained components","Centralize model construction in one factory function to avoid argument drift"],"tags":["configuration","constructor","api-misuse","faster-rcnn"],"backgroundTag":"conflicting-constructor-arguments","analyzedSha":"1ec3fe6f374fc9969973a61f819de25658595afa","analyzedAt":"2026-08-30T09:19:11.901Z","schemaVersion":2},"datasetVersion":"2026-08-30T13:17:10.514Z"}