{"record":{"id":"8a2d8acd068597e2","repo":"WZMIAOMIAO/deep-learning-for-image-processing","slug":"num-classes-should-not-be-none-when-box-predictor","errorCode":null,"errorMessage":"num_classes should not be None when box_predictor is not specified","messagePattern":"num_classes should not be None when box_predictor is not specified","errorType":"validation","errorClass":"ValueError","httpStatus":null,"severity":"error","filePath":"pytorch_object_detection/faster_rcnn/network_files/faster_rcnn_framework.py","lineNumber":282,"sourceCode":"                 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通过滑动窗口预测网络部分\n        if rpn_head is None:\n            rpn_head = RPNHead(\n                out_channels, rpn_anchor_generator.num_anchors_per_location()[0]\n            )","sourceCodeStart":264,"sourceCodeEnd":300,"githubUrl":"https://github.com/WZMIAOMIAO/deep-learning-for-image-processing/blob/1ec3fe6f374fc9969973a61f819de25658595afa/pytorch_object_detection/faster_rcnn/network_files/faster_rcnn_framework.py#L264-L300","documentation":"FasterRCNN.__init__ requires exactly one of two configuration modes: either build the predictor internally from `num_classes`, or receive a fully-built `box_predictor`. Passing neither (num_classes=None and box_predictor=None) is ambiguous, so the constructor raises ValueError to fail fast.","triggerScenarios":"Calling FasterRCNN(backbone, ...) with neither num_classes nor box_predictor supplied, e.g. FasterRCNN(backbone) after copying only the backbone from a pretrained model.","commonSituations":"Copying a backbone from a pretrained model and forgetting to pass either the pretrained box_predictor or the new num_classes; refactoring code that removed one argument but not the other.","solutions":["Pass num_classes=N (including background class, e.g. 91 for COCO, 21 for VOC) when constructing the network from a backbone","Or pass a pre-built box_predictor (e.g. taken from the pretrained fast_rcnn_predictor) instead of num_classes","Ensure the backbone passed in exposes an `out_channels` attribute as required by the constructor"],"exampleFix":"// before\nmodel = FasterRCNN(backbone)\n// after\nmodel = FasterRCNN(backbone, num_classes=91)\n// or\nmodel = FasterRCNN(backbone, box_rpn=None, box_predictor=pretrained_predictor)","handlingStrategy":"validation","validationCode":"assert (num_classes is not None) != (box_predictor is not None), \"Provide exactly one of num_classes or box_predictor\"\nmodel = FasterRCNN(backbone, num_classes=num_classes, box_predictor=box_predictor)","typeGuard":"def has_predictor_config(model_cfg) -> bool:\n    return (model_cfg.get(\"num_classes\") is not None) != (model_cfg.get(\"box_predictor\") is not None)","tryCatchPattern":"try:\n    model = FasterRCNN(backbone, num_classes=num_classes)\nexcept ValueError as e:\n    if \"num_classes should not be None\" in str(e):\n        model = FasterRCNN(backbone, num_classes=num_classes or 91)","preventionTips":["Always pass num_classes (including background) when training from a custom backbone","When loading a pretrained model, pass its box_predictor instead of num_classes","Add a config sanity check asserting exactly one of the two is set"],"tags":["python","valueerror","constructor","object-detection"],"backgroundTag":"required-constructor-argument-missing","analyzedSha":"1ec3fe6f374fc9969973a61f819de25658595afa","analyzedAt":"2026-08-30T09:19:11.901Z","schemaVersion":2},"datasetVersion":"2026-08-30T13:17:10.514Z"}