{"record":{"id":"5daa1ebcab70011d","repo":"WZMIAOMIAO/deep-learning-for-image-processing","slug":"backbone-should-contain-an-attribute-out-channelss-5daa1e","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/mask_rcnn/network_files/faster_rcnn_framework.py","lineNumber":266,"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":248,"sourceCodeEnd":284,"githubUrl":"https://github.com/WZMIAOMIAO/deep-learning-for-image-processing/blob/1ec3fe6f374fc9969973a61f819de25658595afa/pytorch_object_detection/mask_rcnn/network_files/faster_rcnn_framework.py#L248-L284","documentation":"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.","triggerScenarios":"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.","commonSituations":"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.","solutions":["Add self.out_channels = <int> to your custom backbone class (e.g. 256 after FPN, 2048 for raw ResNet-50 C4)","Wrap the model with torchvision's BackboneWithFPN, which sets out_channels automatically","Verify the attribute exists: assert hasattr(backbone, 'out_channels') before constructing the detector"],"exampleFix":"// before\nclass MyBackbone(nn.Module):\n    def __init__(self):\n        super().__init__()\n        self.body = resnet50()\n// after\nclass MyBackbone(nn.Module):\n    def __init__(self):\n        super().__init__()\n        self.body = resnet50()\n        self.out_channels = 2048","handlingStrategy":"validation","validationCode":"assert hasattr(backbone, 'out_channels'), 'backbone must define out_channels before building FasterRCNN'","typeGuard":"def has_out_channels(backbone):\n    return hasattr(backbone, 'out_channels') and isinstance(backbone.out_channels, int) and backbone.out_channels > 0","tryCatchPattern":"try:\n    model = FasterRCNN(backbone, num_classes=num_classes)\nexcept ValueError as e:\n    if 'out_channels' in str(e):\n        backbone = BackboneWithFPN(backbone.body, return_layers, 256)\n        model = FasterRCNN(backbone, num_classes=num_classes)\n    else:\n        raise","preventionTips":["Use BackboneWithFPN or torchvision's pretrained backbone builders that set out_channels","Document out_channels as a required contract for custom backbones","Assert hasattr(backbone, 'out_channels') in backbone unit tests"],"tags":["pytorch","config","backbone"],"backgroundTag":"missing-attribute","analyzedSha":"1ec3fe6f374fc9969973a61f819de25658595afa","analyzedAt":"2026-08-30T09:19:11.901Z","schemaVersion":2},"datasetVersion":"2026-08-30T13:17:10.514Z"}