HI, I have a toy densenet model (e.g. only one dense block, a copy from official implementation) with TWO variables (x,y) for the denseblock. However, there is an error " result = self.forward(*input, **kwargs) TypeError: forward() takes 2 positional arguments but 3 were given". This model works for only one variable (x) . Currenty, I can still not figure out the reason and was wondering if there is something wrong in the nn.Sequential(*layers) part? Thanks in advance!
class BasicBlock(nn.Module): def __init__(self, in_planes, out_planes): super(BasicBlock, self).__init__() self.bn1 = nn.BatchNorm2d(in_planes) self.relu = nn.ReLU(inplace=True) self.conv1 = nn.Conv2d(in_planes, out_planes, kernel_size=3, stride=1, padding=1, bias=False) def forward(self, x,y): out1 = self.conv1(self.relu(self.bn1(x))) out2 = y return torch.cat([x, out1], 1), out2 class DenseBlock(nn.Module): def __init__(self, nb_layers, in_planes, growth_rate, block): super(DenseBlock, self).__init__() self.layer = self._make_layer(block, in_planes, growth_rate, nb_layers) def _make_layer(self, block, in_planes, growth_rate, nb_layers): layers =  for i in range(nb_layers): layers.append(block(in_planes+i*growth_rate, growth_rate)) return nn.Sequential(*layers) # return block(in_planes+growth_rate, growth_rate) #It works by replacing the whole "for" loop with this line, but we can only obtain one block rather than nb_layes blocks. def forward(self, x,y): return self.layer(x,y) class DenseNet3(nn.Module): def __init__(self, n=2, growth_rate=8): super(DenseNet3, self).__init__() in_planes = growth_rate block = BasicBlock # 1st conv before any dense block self.conv1 = nn.Conv2d(3, in_planes, kernel_size=5, stride=1, padding=0, bias=False) # 1st block self.block1 = DenseBlock(n, in_planes, growth_rate, block) in_planes = int(in_planes+n*growth_rate) #### # 2st block ... # 3st block ... def forward(self, x,y): x = self.conv1(x) out1, out2 = self.block1(x,y) # 2nd, 3rd blocks ... return out1, out2
Error: File “/home/…/densenet.py”, line 33, in forward
return self.layer(x,y) (in class DenseBlock)
File “/home/…/miniconda3/envs/Detector/lib/python3.6/site-packages/torch/nn/modules/module.py”, line 489, in call
result = self.forward(*input, **kwargs)
TypeError: forward() takes 2 positional arguments but 3 were given