pytorch报错(4)forward() missing 1 required positional argument: ‘x‘或者‘NoneType‘ object is not callable

解决:TypeErro: ‘NoneType’ object is not callable/forward()
TypeErro: forward() missing 1 required positional argument: 'x’


前言

我们在构建自己的神经网络类时,经常要在现有的pytorch模型下修改,然后将修改好的类封装到一个新的py文件中,在封装过程中可能遇到如下两种错误:
TypeErro: ‘NoneType’ object is not callable/forward()
TypeErro: forward() missing 1 required positional argument: 'x’

提示:以下是本篇文章正文内容,下面案例可供参考

一、首先展示正确封装的代码

以VGG16为例,我们经常会基于pytorch官网封装的torchvision.models.vgg16()进行修改,这里我们在vgg16 的最后添加一层全连接层,100输入,10输出,并封装为一个py文件,方便日后调用。

#基于vgg16进行修改、封装
#把改进的ImageNet网络存储起来
import torchvision
import torch
from torch import nn

ImageNet = torchvision.models.vgg16(pretrained=True, progress=True)
ImageNet.classifier.add_module("linear", nn.Linear(1000, 10))
class my_net(nn.Module):
    def __init__(self):
        super().__init__()
        self.model = ImageNet

    def forward(self, x):
        output = self.model(x)
        return output

if __name__ == '__main__':
    my_model2 = my_net()
    input = torch.ones((1, 3, 32, 32))
    output = my_model2(input)
    print(output.shape)

这样写是没有报错的,可以整段复制,运行结果如下图(main函数只是测试一下网络是否可以正常输出)。
在这里插入图片描述

接下来看一下错误的例子及其报出的错误。

二、两种错误

1.TypeError: forward() missing 1 required positional argument: ‘x’

如果上文第12行self.model = ImageNet后面加了括号,即:self.model = ImageNet(),那么就会报错TypeError: forward() missing 1 required positional argument: ‘x’

2.TypeErro: ‘NoneType’ object is not callable/forward()

如果你把第8行 ImageNet.classifier.add_module(“linear”, nn.Linear(1000, 10)) 直接赋给第12行的self.model ,那么就会报错 TypeErro: ‘NoneType’ object is not callable/forward()
在这里插入图片描述

总结

pytorch中可能一个看起来很正常的括号就会引发错误。建议先在类class外修改好神经网络,然后直接调用修改好的模型名称。
如果有帮助的话,请顺手点赞,谢谢。

  • 19
    点赞
  • 23
    收藏
    觉得还不错? 一键收藏
  • 3
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值