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

backbone should contain an attribute out_channelsspecifying

Error message

backbone should contain an attribute out_channelsspecifying the number of output channels  (assumed to be thesame for all the levels

What it means

fasterrcnn.__init__ (the custom fasterrcnn_resnet50_fpn-style builder) requires the backbone to expose an `out_channels` attribute telling the framework how many channels each feature level outputs, needed to build the FPN and RPN heads. If hasattr(backbone, 'out_channels') is False it raises this ValueError (note the typo: missing space — 'out_channelsspecifying').

Source

Thrown at pytorch_object_detection/faster_rcnn/network_files/faster_rcnn_framework.py:267

                 min_size=800, max_size=1333,      # 预处理resize时限制的最小尺寸与最大尺寸
                 image_mean=None, image_std=None,  # 预处理normalize时使用的均值和方差
                 # RPN parameters
                 rpn_anchor_generator=None, rpn_head=None,
                 rpn_pre_nms_top_n_train=2000, rpn_pre_nms_top_n_test=1000,    # rpn中在nms处理前保留的proposal数(根据score)
                 rpn_post_nms_top_n_train=2000, rpn_post_nms_top_n_test=1000,  # rpn中在nms处理后保留的proposal数
                 rpn_nms_thresh=0.7,  # rpn中进行nms处理时使用的iou阈值
                 rpn_fg_iou_thresh=0.7, rpn_bg_iou_thresh=0.3,  # rpn计算损失时,采集正负样本设置的阈值
                 rpn_batch_size_per_image=256, rpn_positive_fraction=0.5,  # rpn计算损失时采样的样本数,以及正样本占总样本的比例
                 rpn_score_thresh=0.0,
                 # Box parameters
                 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

View on GitHub (pinned to 1ec3fe6f37)

Solutions

  1. Set the attribute: backbone.out_channels = <num channels of feature maps> (e.g. 256 after FPN).
  2. Wrap your backbone with network_files.backbone.BackboneWithFPN, which sets out_channels for you.
  3. If using a plain single-scale backbone, ensure it returns a feature dict/OrderedDict and set out_channels to that channel count.
  4. Check spelling: it must be exactly out_channels, not out_channel.

Example fix

# before
backbone = torchvision.models.resnet50()  # no out_channels attribute
model = fasterrcnn(backbone=backbone, num_classes=91)
# after
backbone = torchvision.models.resnet50(weights='IMAGENET1K_V1')
returned_layers = [1, 2, 3, 4]
return_layers = {str(k): str(v) for k, v in zip(range(5), returned_layers)}
in_channels = [256, 512, 1024, 2048]
backbone = BackboneWithFPN(backbone, return_layers, in_channels, out_channels=256)
model = fasterrcnn(backbone=backbone, num_classes=91)
Defensive patterns

Strategy: validation

Validate before calling

assert hasattr(backbone, 'out_channels'), "backbone must set out_channels (e.g. backbone.out_channels = 256)"

Type guard

def has_out_channels(backbone) -> bool:
    return hasattr(backbone, 'out_channels') and isinstance(backbone.out_channels, int)

Try / catch

try:
    model = fasterrcnn(backbone=backbone, num_classes=num_classes)
except ValueError as e:
    if 'out_channels' in str(e):
        raise RuntimeError("Wrap backbone with BackboneWithFPN or set backbone.out_channels") from e
    raise

Prevention

When it happens

Trigger: Passing a raw nn.Module backbone (e.g. a bare resnet50 or a custom CNN) that was never wrapped with a container setting out_channels, into fasterrcnn(...) or fasterrcnn_resnet50_fpn(backbone=...) style construction.

Common situations: Replacing the backbone with a custom network but forgetting backbone.out_channels = C; passing torchvision's truncated feature module directly instead of BackboneWithFPN output; typo'ing the attribute name.

Related errors


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