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
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.
Source
Thrown at pytorch_object_detection/faster_rcnn/network_files/faster_rcnn_framework.py:282
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
- 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
Example fix
// before model = FasterRCNN(backbone) // after model = FasterRCNN(backbone, num_classes=91) // or model = FasterRCNN(backbone, box_rpn=None, box_predictor=pretrained_predictor)
Defensive patterns
Strategy: validation
Validate before calling
assert (num_classes is not None) != (box_predictor is not None), "Provide exactly one of num_classes or box_predictor" model = FasterRCNN(backbone, num_classes=num_classes, box_predictor=box_predictor)
Type guard
def has_predictor_config(model_cfg) -> bool:
return (model_cfg.get("num_classes") is not None) != (model_cfg.get("box_predictor") is not None) Try / catch
try:
model = FasterRCNN(backbone, num_classes=num_classes)
except ValueError as e:
if "num_classes should not be None" in str(e):
model = FasterRCNN(backbone, num_classes=num_classes or 91) Prevention
- 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
When it happens
Trigger: Calling FasterRCNN(backbone, ...) with neither num_classes nor box_predictor supplied, e.g. FasterRCNN(backbone) after copying only the backbone from a pretrained model.
Common situations: 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.
Related errors
- expected stages_repeats as list of 3 positive ints
- expected stages_out_channels as list of 5 positive ints
- image: {} isn't RGB mode.
- dataset have {} classes, but input {}
- dataset have {} classes, but input {}
AI-assisted analysis of WZMIAOMIAO/deep-learning-for-image-processing@1ec3fe6f37 (2026-08-30).
Data as JSON: /api/errors/8a2d8acd068597e2.
Report an issue: GitHub.