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 given AND a prebuilt box_predictor is supplied, the class count is ambiguous (the predictor already encodes its own output size), so it raises this ValueError.
Source
Thrown at pytorch_object_detection/mask_rcnn/network_files/faster_rcnn_framework.py:277
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 a custom box_predictor, pass num_classes=None
- When you want the library to build the predictor, pass box_predictor=None and only num_classes
- Replace the predictor after construction instead: build the model with num_classes, then swap model.roi_heads.box_predictor
Example fix
// before
model = fasterrcnn_resnet50_fpn(pretrained=True, num_classes=5,
box_predictor=FastRCNNPredictor(1024, 5))
// after
model = fasterrcnn_resnet50_fpn(pretrained=True, box_predictor=FastRCNNPredictor(1024, 5)) # 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'
Try / catch
try:
model = FasterRCNN(backbone, num_classes=num_classes, box_predictor=box_predictor)
except ValueError as e:
if 'should be None when box_predictor' in str(e):
model = FasterRCNN(backbone, box_predictor=box_predictor)
else:
raise Prevention
- Pick one customization recipe: either num_classes OR a prebuilt predictor
- When swapping predictors post-construction, never also pass num_classes
- Review constructor kwargs before commit; both keys together is always a bug
When it happens
Trigger: Calling fasterrcnn_resnet50_fpn(pretrained=True, num_classes=..., box_predictor=FastRCNNPredictor(...)) or FasterRCNN(..., num_classes=91, box_predictor=my_predictor) — i.e. specifying both at once.
Common situations: Fine-tuning tutorials where users replace box_predictor but forget to drop num_classes; copy-pasting constructor args from two different customization recipes.
Related errors
- num_classes should not be None when box_predictor is not spe
- illegal stride value.
- The inverted_residual_setting should not be empty.
- The inverted_residual_setting should be List[InvertedResidua
- expected stages_repeats as list of 3 positive ints
AI-assisted analysis of WZMIAOMIAO/deep-learning-for-image-processing@1ec3fe6f37 (2026-08-30).
Data as JSON: /api/errors/0437ef70be36078a.
Report an issue: GitHub.