查阅了很多有关NoneType object is not callable
的博文。大多都是因为在不可调用对象上添加上了(),解决方法也很easy:去掉调用函数的 ‘( )’ 即可。具体可以查看这篇博文。但是,我在搭建神经网络时遇到的这个问题,却用到了不同的解决方法。
先来看我对网络的定义:
class ConvNet(nn.Module):
def __init__(self):
super(ConvNet, self).__init__()
self.conv1 = nn.Sequential(
nn.Conv2d(in_channels=1, out_channels=16, kernel_size=4, stride=1, padding=1),
nn.ReLU(), # 激活函数
nn.AvgPool2d(kernel_size=2, stride=2)
)
self.conv2 = nn.Sequential(
nn.Conv2d(in_channels=16, out_channels=32, kernel_size=5, stride=1, padding=1),
nn.ReLU(), # 激活函数
nn.MaxPool2d(2, 2) # 最大值池化
)
self.fc = nn.Sequential(
print("执行1"),
nn.Linear(in_features=32 * 5 * 5, out_features=128),
print("执行2"),
nn.ReLU(), # 激活函数
print("执行3"),
nn.Linear(in_features=128, out_features=64),
print("执行4"),
nn.ReLU(), # 激活函数
print("执行5"),
nn.Linear(in_features=64, out_features=32),
print("执行6"),
nn.ReLU(), # 激活函数
print("执行7"),
)
self.out = nn.Linear(32, 10) # 最后的分类层
def forward(self, x):
print("TAG1",x.shape)
x = self.conv1(x)
print("TAG2", x.shape)
x = self.conv2(x)
print("TAG3", x.shape)
x = x.view(x.size(0), -1) # 展平多维卷积图层
print("TAG4", x.shape)
x = self.fc(x)
print("TAG5", x.shape)
output = self.out(x)
print("TAG6", output.shape)
return output
接下来直接给出解决方法:
在nn.Sequential中不允许使用print语句。解决方法是删除掉nn.sequential中的所有print语句即可。删除后的代码如下所示:
# 其余部分都没有改变,只有nn.sequential部分发生了改变
self.fc = nn.Sequential(
nn.Linear(in_features=32 * 5 * 5, out_features=128),
nn.ReLU(), # 激活函数
nn.Linear(in_features=128, out_features=64),
nn.ReLU(), # 激活函数
nn.Linear(in_features=64, out_features=32),
nn.ReLU(), # 激活函数
)