{"record":{"id":"7ac0035a39a55ce9","repo":"WZMIAOMIAO/deep-learning-for-image-processing","slug":"backbone-should-contain-an-attribute-out-channelss","errorCode":null,"errorMessage":"backbone should contain an attribute out_channelsspecifying the number of output channels  (assumed to be thesame for all the levels","messagePattern":"backbone should contain an attribute out_channelsspecifying the number of output channels  \\(assumed to be thesame for all the levels","errorType":"validation","errorClass":"ValueError","httpStatus":null,"severity":"error","filePath":"pytorch_object_detection/faster_rcnn/network_files/faster_rcnn_framework.py","lineNumber":267,"sourceCode":"                 min_size=800, max_size=1333,      # 预处理resize时限制的最小尺寸与最大尺寸\n                 image_mean=None, image_std=None,  # 预处理normalize时使用的均值和方差\n                 # RPN parameters\n                 rpn_anchor_generator=None, rpn_head=None,\n                 rpn_pre_nms_top_n_train=2000, rpn_pre_nms_top_n_test=1000,    # rpn中在nms处理前保留的proposal数(根据score)\n                 rpn_post_nms_top_n_train=2000, rpn_post_nms_top_n_test=1000,  # rpn中在nms处理后保留的proposal数\n                 rpn_nms_thresh=0.7,  # rpn中进行nms处理时使用的iou阈值\n                 rpn_fg_iou_thresh=0.7, rpn_bg_iou_thresh=0.3,  # rpn计算损失时，采集正负样本设置的阈值\n                 rpn_batch_size_per_image=256, rpn_positive_fraction=0.5,  # rpn计算损失时采样的样本数，以及正样本占总样本的比例\n                 rpn_score_thresh=0.0,\n                 # Box parameters\n                 box_roi_pool=None, box_head=None, box_predictor=None,\n                 # 移除低目标概率      fast rcnn中进行nms处理的阈值   对预测结果根据score排序取前100个目标\n                 box_score_thresh=0.05, box_nms_thresh=0.5, box_detections_per_img=100,\n                 box_fg_iou_thresh=0.5, box_bg_iou_thresh=0.5,   # fast rcnn计算误差时，采集正负样本设置的阈值\n                 box_batch_size_per_image=512, box_positive_fraction=0.25,  # fast rcnn计算误差时采样的样本数，以及正样本占所有样本的比例\n                 bbox_reg_weights=None):\n        if not hasattr(backbone, \"out_channels\"):\n            raise ValueError(\n                \"backbone should contain an attribute out_channels\"\n                \"specifying the number of output channels  (assumed to be the\"\n                \"same for all the levels\"\n            )\n\n        assert isinstance(rpn_anchor_generator, (AnchorsGenerator, type(None)))\n        assert isinstance(box_roi_pool, (MultiScaleRoIAlign, type(None)))\n\n        if num_classes is not None:\n            if box_predictor is not None:\n                raise ValueError(\"num_classes should be None when box_predictor \"\n                                 \"is specified\")\n        else:\n            if box_predictor is None:\n                raise ValueError(\"num_classes should not be None when box_predictor \"\n                                 \"is not specified\")\n\n        # 预测特征层的channels","sourceCodeStart":249,"sourceCodeEnd":285,"githubUrl":"https://github.com/WZMIAOMIAO/deep-learning-for-image-processing/blob/1ec3fe6f374fc9969973a61f819de25658595afa/pytorch_object_detection/faster_rcnn/network_files/faster_rcnn_framework.py#L249-L285","documentation":"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').","triggerScenarios":"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.","commonSituations":"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.","solutions":["Set the attribute: backbone.out_channels = <num channels of feature maps> (e.g. 256 after FPN).","Wrap your backbone with network_files.backbone.BackboneWithFPN, which sets out_channels for you.","If using a plain single-scale backbone, ensure it returns a feature dict/OrderedDict and set out_channels to that channel count.","Check spelling: it must be exactly out_channels, not out_channel."],"exampleFix":"# before\nbackbone = torchvision.models.resnet50()  # no out_channels attribute\nmodel = fasterrcnn(backbone=backbone, num_classes=91)\n# after\nbackbone = torchvision.models.resnet50(weights='IMAGENET1K_V1')\nreturned_layers = [1, 2, 3, 4]\nreturn_layers = {str(k): str(v) for k, v in zip(range(5), returned_layers)}\nin_channels = [256, 512, 1024, 2048]\nbackbone = BackboneWithFPN(backbone, return_layers, in_channels, out_channels=256)\nmodel = fasterrcnn(backbone=backbone, num_classes=91)","handlingStrategy":"validation","validationCode":"assert hasattr(backbone, 'out_channels'), \"backbone must set out_channels (e.g. backbone.out_channels = 256)\"","typeGuard":"def has_out_channels(backbone) -> bool:\n    return hasattr(backbone, 'out_channels') and isinstance(backbone.out_channels, int)","tryCatchPattern":"try:\n    model = fasterrcnn(backbone=backbone, num_classes=num_classes)\nexcept ValueError as e:\n    if 'out_channels' in str(e):\n        raise RuntimeError(\"Wrap backbone with BackboneWithFPN or set backbone.out_channels\") from e\n    raise","preventionTips":["Set backbone.out_channels whenever you write a custom backbone","Prefer BackboneWithFPN which sets the attribute automatically","Watch the attribute name exactly: out_channels","Test model construction on a dummy input before full training"],"tags":["backbone","fpn","configuration","attribute-error"],"backgroundTag":"backbone-missing-out-channels","analyzedSha":"1ec3fe6f374fc9969973a61f819de25658595afa","analyzedAt":"2026-08-30T09:19:11.901Z","schemaVersion":2},"datasetVersion":"2026-08-30T13:17:10.514Z"}