{"record":{"id":"2c61cd75a29a743a","repo":"WZMIAOMIAO/deep-learning-for-image-processing","slug":"num-classes-should-not-be-none-when-box-predictor-2c61cd","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/mask_rcnn/network_files/faster_rcnn_framework.py","lineNumber":281,"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":263,"sourceCodeEnd":299,"githubUrl":"https://github.com/WZMIAOMIAO/deep-learning-for-image-processing/blob/1ec3fe6f374fc9969973a61f819de25658595afa/pytorch_object_detection/mask_rcnn/network_files/faster_rcnn_framework.py#L263-L299","documentation":"The complementary check to error 77: if neither num_classes nor box_predictor is provided, the ROI box head cannot know how many classes to predict, so __init__ raises this ValueError.","triggerScenarios":"Calling FasterRCNN(...) (or the fasterrcnn_* factory with a custom backbone) with both box_predictor=None and num_classes=None.","commonSituations":"Building a detector with a custom backbone and forgetting num_classes; refactoring code that removed a num_classes argument; loading a config where num_classes defaults to None.","solutions":["Pass num_classes=<num_classes+1 background> when constructing the model","Or supply a prebuilt box_predictor sized for your class count instead of num_classes","If loading weights for transfer learning, construct with the correct num_classes then load the backbone weights"],"exampleFix":"// before\nmodel = fasterrcnn_resnet50_fpn(pretrained=True)  # factory default num_classes is fine, but custom path:\nmodel = FasterRCNN(backbone)  # neither given\n// after\nmodel = FasterRCNN(backbone, num_classes=91)  # 90 classes + background","handlingStrategy":"validation","validationCode":"assert num_classes is not None or box_predictor is not None, 'FasterRCNN needs num_classes or a prebuilt box_predictor'","typeGuard":null,"tryCatchPattern":"try:\n    model = FasterRCNN(backbone, num_classes=num_classes)\nexcept ValueError as e:\n    if 'should not be None when box_predictor' in str(e):\n        model = FasterRCNN(backbone, num_classes=default_num_classes)\n    else:\n        raise","preventionTips":["Always specify num_classes = dataset_classes + 1 (background) when building detectors","Centralize detector construction in one factory function with a required num_classes parameter","Validate config files set num_classes before model creation"],"tags":["pytorch","config","api-misuse"],"backgroundTag":"missing-required-argument","analyzedSha":"1ec3fe6f374fc9969973a61f819de25658595afa","analyzedAt":"2026-08-30T09:19:11.901Z","schemaVersion":2},"datasetVersion":"2026-08-30T13:17:10.514Z"}