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

The FasterRCNN constructor reads backbone.out_channels to size the FPN/RPN heads. If the supplied backbone lacks an out_channels attribute, the number of output feature channels is unknown, so __init__ raises this ValueError.

Source

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

                 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. Add self.out_channels = <int> to your custom backbone class (e.g. 256 after FPN, 2048 for raw ResNet-50 C4)
  2. Wrap the model with torchvision's BackboneWithFPN, which sets out_channels automatically
  3. Verify the attribute exists: assert hasattr(backbone, 'out_channels') before constructing the detector

Example fix

// before
class MyBackbone(nn.Module):
    def __init__(self):
        super().__init__()
        self.body = resnet50()
// after
class MyBackbone(nn.Module):
    def __init__(self):
        super().__init__()
        self.body = resnet50()
        self.out_channels = 2048
Defensive patterns

Strategy: validation

Validate before calling

assert hasattr(backbone, 'out_channels'), 'backbone must define out_channels before building FasterRCNN'

Type guard

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

Try / catch

try:
    model = FasterRCNN(backbone, num_classes=num_classes)
except ValueError as e:
    if 'out_channels' in str(e):
        backbone = BackboneWithFPN(backbone.body, return_layers, 256)
        model = FasterRCNN(backbone, num_classes=num_classes)
    else:
        raise

Prevention

When it happens

Trigger: Passing a raw nn.Module backbone (e.g. torchvision resnet50 without FPN wrapper) directly to fasterrcnn_resnet50_fpn-style constructors or FasterRCNN(...) instead of a backbone wrapped with BackboneWithFPN / a custom backbone exposing out_channels.

Common situations: Using a custom CNN as backbone without defining self.out_channels; replacing a pretrained backbone at runtime; mixing backbones built for feature-extraction APIs with torchvision-style GeneralizedRCNN constructors.

Related errors


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