【问题标题】:PyTorch FasterRCNN TypeError: forward() takes 2 positional arguments but 3 were givenPyTorch FasterRCNN TypeError: forward() 接受 2 个位置参数,但给出了 3 个
【发布时间】:2020-06-16 04:51:40
【问题描述】:

我正在研究对象检测,我有一个包含图像及其相应边界框(真实值)的数据集。

我实际上已经构建了自己的特征提取器,它将图像作为输入并输出特征图(基本上是一个编码器-解码器系统,其中解码器的最终输出与图像大小相同,并且具有 3 个通道)。现在,我想将此特征图作为输入提供给 FasterRCNN 模型进行检测,而不是原始图像。我正在使用以下代码在 FRCNN 检测模块顶部添加特征图(使用 RTFNet 生成特征图 - 代码在此link

frcnn_model = fasterrcnn_resnet50_fpn(pretrained=True)
in_features = frcnn_model.roi_heads.box_predictor.cls_score.in_features
frcnn_model.roi_heads.box_predictor = FastRCNNPredictor(in_features, num_classes)
fpn_block = frcnn_model.backbone.fpn
rpn_block = frcnn_model.rpn

backbone = RTFNet(num_classes) RTFNet is a feature extractor taking as input, an image having 4 channels(fused RGB and thermal image) , 
model = nn.Sequential(backbone, nn.ReLU(inplace=True))
model = nn.Sequential(model,fpn_block)
model = nn.Sequential(model,rpn_block)
model = nn.Sequential(model,FastRCNNPredictor(in_features, num_classes))

我只是想通过使用以下生成随机图像和边界框的代码来测试它是否正常工作

images, boxes = torch.rand(1, 4, 512, 640), torch.rand(4, 11, 4)
labels = torch.randint(1, num_classes, (4, 11))
images = list(image for image in images)
targets = []
for i in range(len(images)):
  d = {}
  d['boxes'] = boxes[i]
  d['labels'] = labels[i]
  targets.append(d)
output = model(images, targets)

运行它会给我以下错误

TypeError                                 Traceback (most recent call last)
<ipython-input-22-2637b8c27ad2> in <module>()
----> 1 output = model(images, targets)

/usr/local/lib/python3.6/dist-packages/torch/nn/modules/module.py in __call__(self, *input, **kwargs)
    530             result = self._slow_forward(*input, **kwargs)
    531         else:
--> 532             result = self.forward(*input, **kwargs)
    533         for hook in self._forward_hooks.values():
    534             hook_result = hook(self, input, result)

TypeError: forward() takes 2 positional arguments but 3 were given

但是,当我用普通的 FasterRCNN 模型替换我的模型时,

model = fasterrcnn_resnet50_fpn(pretrained=True)
in_features = model.roi_heads.box_predictor.cls_score.in_features
model.roi_heads.box_predictor = FastRCNNPredictor(in_features, num_classes)

没有错误,工作正常

谁能告诉我哪里出错了?提前致谢

【问题讨论】:

    标签: python pytorch object-detection faster-rcnn torchvision


    【解决方案1】:

    这是因为只有图像输入应该被传递到模型中,而不是图像和地面实况目标。所以不用output = model(images, targets),你可以用output = model(images)

    至于为什么错误信息会提到被赋予 3 个位置参数,这是因为 forward 是使用默认的 self 关键字启动的,它代表类实例。因此,除了self,您应该只再提供 1 个参数,即输入图像。

    【讨论】:

    • 好的,但是我应该如何以及在哪里通过目标?
    • 想一想,模型预测从不依赖于ground truth注释。因此,目标仅在评估预测的准确性时才会通过,并传递到您的损失函数中。
    • 是的,这绝对是有道理的。感谢您的澄清。但是,当我只传递图像而不传递训练标签时,我得到一个值错误,表示在训练时必须传递目标。 ValueError:在训练模式下,应该通过目标整个回溯在这个link。有什么解决方法吗?
    • 我好像无权访问链接?
    猜你喜欢
    • 2021-09-01
    • 2021-08-20
    • 1970-01-01
    • 1970-01-01
    • 2021-07-06
    • 1970-01-01
    • 2021-02-02
    • 1970-01-01
    • 2020-03-27
    相关资源
    最近更新 更多