WZMIAOMIAO/deep-learning-for-image-processing · error · ValueError

num_classes should not be None when box_predictor is not spe

Error message

num_classes should not be None when box_predictor is not specified

What it means

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.

Source

Thrown at pytorch_object_detection/mask_rcnn/network_files/faster_rcnn_framework.py:281

                 box_batch_size_per_image=512, box_positive_fraction=0.25,  # fast rcnn计算误差时采样的样本数,以及正样本占所有样本的比例
                 bbox_reg_weights=None):
        if not hasattr(backbone, "out_channels"):
            raise ValueError(
                "backbone should contain an attribute out_channels"
                "specifying the number of output channels  (assumed to be the"
                "same for all the levels"
            )

        # assert isinstance(rpn_anchor_generator, (AnchorsGenerator, type(None)))
        assert isinstance(box_roi_pool, (MultiScaleRoIAlign, type(None)))

        if num_classes is not None:
            if box_predictor is not None:
                raise ValueError("num_classes should be None when box_predictor "
                                 "is specified")
        else:
            if box_predictor is None:
                raise ValueError("num_classes should not be None when box_predictor "
                                 "is not specified")

        # 预测特征层的channels
        out_channels = backbone.out_channels

        # 若anchor生成器为空,则自动生成针对resnet50_fpn的anchor生成器
        if rpn_anchor_generator is None:
            anchor_sizes = ((32,), (64,), (128,), (256,), (512,))
            aspect_ratios = ((0.5, 1.0, 2.0),) * len(anchor_sizes)
            rpn_anchor_generator = AnchorsGenerator(
                anchor_sizes, aspect_ratios
            )

        # 生成RPN通过滑动窗口预测网络部分
        if rpn_head is None:
            rpn_head = RPNHead(
                out_channels, rpn_anchor_generator.num_anchors_per_location()[0]
            )

View on GitHub (pinned to 1ec3fe6f37)

Solutions

  1. Pass num_classes=<num_classes+1 background> when constructing the model
  2. Or supply a prebuilt box_predictor sized for your class count instead of num_classes
  3. If loading weights for transfer learning, construct with the correct num_classes then load the backbone weights

Example fix

// before
model = fasterrcnn_resnet50_fpn(pretrained=True)  # factory default num_classes is fine, but custom path:
model = FasterRCNN(backbone)  # neither given
// after
model = FasterRCNN(backbone, num_classes=91)  # 90 classes + background
Defensive patterns

Strategy: validation

Validate before calling

assert num_classes is not None or box_predictor is not None, 'FasterRCNN needs num_classes or a prebuilt box_predictor'

Try / catch

try:
    model = FasterRCNN(backbone, num_classes=num_classes)
except ValueError as e:
    if 'should not be None when box_predictor' in str(e):
        model = FasterRCNN(backbone, num_classes=default_num_classes)
    else:
        raise

Prevention

When it happens

Trigger: Calling FasterRCNN(...) (or the fasterrcnn_* factory with a custom backbone) with both box_predictor=None and num_classes=None.

Common situations: 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.

Understand the failure class

Background: "missing required argument" and "the following required arguments were not provided": what required-argument errors mean and how to fix them — this error's family across 20 libraries.

Related errors


AI-assisted analysis of WZMIAOMIAO/deep-learning-for-image-processing@1ec3fe6f37 (2026-08-30). Data as JSON: /api/errors/2c61cd75a29a743a. Report an issue: GitHub.