使用Pytorch编写网络时,有时遇到 TypeError:‘tuple‘ object is not callable 错误。
bug原因:在编写网络时,因为习惯或者不注意在其中一层网络结尾时添加了逗号“,”。
如下所示:
class BlockA(nn.Module):
def __init__(self, in_channels, out_channels,downsample=None, stride=1):
super(BlockA, self).__init__()
self.conv1 = nn.Conv2d(in_channels, out_channels, kernel_size=3, padding=1, stride=stride)
self.conv2 = nn.Conv2d(out_channels, out_channels, kernel_size=3, padding=1)
self.leakyrelu = nn.LeakyReLU(0.1),
def forward(self, X):
Y = self.conv1(X)
Y = self.leakyrelu(Y)
Y = self.conv2(Y)
return self.leakyrelu(Y + X)
运行会出现如下报错:
正确的应该改为:
class BlockA(nn.Module):
def __init__(self, in_channels, out_channels,downsample=None, stride=1):
super(BlockA, self).__init__()
self.conv1 = nn.Conv2d(in_channels, out_channels, kernel_size=3, padding=1, stride=stride)
self.conv2 = nn.Conv2d(out_channels, out_channels, kernel_size=3, padding=1)
self.leakyrelu = nn.LeakyReLU(0.1)
def forward(self, X):
Y = self.conv1(X)
Y = self.leakyrelu(Y)
Y = self.conv2(Y)
return self.leakyrelu(Y + X)