WZMIAOMIAO/deep-learning-for-image-processing · error · ValueError
num_classes should be None when box_predictor is specified
Error message
num_classes should be None when box_predictor is specified
What it means
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).
Source
Thrown at pytorch_object_detection/faster_rcnn/network_files/faster_rcnn_framework.py:278
box_roi_pool=None, box_head=None, box_predictor=None,
# 移除低目标概率 fast rcnn中进行nms处理的阈值 对预测结果根据score排序取前100个目标
box_score_thresh=0.05, box_nms_thresh=0.5, box_detections_per_img=100,
box_fg_iou_thresh=0.5, box_bg_iou_thresh=0.5, # fast rcnn计算误差时,采集正负样本设置的阈值
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通过滑动窗口预测网络部分View on GitHub (pinned to 1ec3fe6f37)
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.
Example fix
# before predictor = FastRCNNPredictor(in_features, num_classes=5) model = fasterrcnn(backbone=backbone, num_classes=5, box_predictor=predictor) # after predictor = FastRCNNPredictor(in_features, num_classes=5) model = fasterrcnn(backbone=backbone, box_predictor=predictor) # num_classes omitted (None)
Defensive patterns
Strategy: validation
Validate before calling
assert not (num_classes is not None and box_predictor is not None), "pass either num_classes or box_predictor, not both"
Type guard
def predictor_args_ok(num_classes, box_predictor) -> bool:
return (num_classes is None) == (box_predictor is None) Try / catch
try:
model = fasterrcnn(backbone=backbone, num_classes=num_classes, box_predictor=box_predictor)
except ValueError as e:
if 'num_classes should be None' in str(e):
model = fasterrcnn(backbone=backbone, box_predictor=box_predictor)
else:
raise Prevention
- 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
When it happens
Trigger: Calling fasterrcnn(backbone=..., num_classes=91, box_predictor=my_predictor) — passing both a custom FastRCNNPredictor and num_classes at once.
Common situations: 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.
Related errors
- In training mode, targets should be passed
- return_layers are not present in model
- backbone should contain an attribute out_channelsspecifying
- num_classes should not be None when box_predictor is not spe
- In training mode, targets should be passed
AI-assisted analysis of WZMIAOMIAO/deep-learning-for-image-processing@1ec3fe6f37 (2026-08-30).
Data as JSON: /api/errors/b897d1da54dfd312.
Report an issue: GitHub.