解决TypeError: ‘NoneType‘ object is not callable的办法

112 篇文章 7 订阅
68 篇文章 6 订阅

查阅了很多有关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(),  # 激活函数
        )
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值