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文件,方便日后调用。


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函数只是测试一下网络是否可以正常输出)。

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

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

二、两种错误

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报错(4)forward() missing 1 required positional argument: ‘x‘或者‘NoneType‘ object is not callable

; 总结

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

Original: https://blog.csdn.net/qq_37382769/article/details/123489066
Author: 香菜冰激凌
Title: pytorch报错(4)forward() missing 1 required positional argument: ‘x‘或者‘NoneType‘ object is not callable

原创文章受到原创版权保护。转载请注明出处:https://www.johngo689.com/625364/

转载文章受原作者版权保护。转载请注明原作者出处!

(0)

大家都在看

亲爱的 Coder【最近整理,可免费获取】👉 最新必读书单  | 👏 面试题下载  | 🌎 免费的AI知识星球