pytorch报错信息:TypeError: __init__() takes 1 positional argument but 2 were given

总共报错如下:

  1. AttributeError: Can't get attribute 'Net' on <module '__main__' from 'E:/xjustudy/pythonproj/jhcproj3/test-001/test_001.py'>
  2. TypeError: __init__() takes 1 positional argument but 2 were given

首先出现这个错误的背景说下:

我自建了一个神经网络(代码如下),然后简单训练了一下,保存这个神经网络的模型,然后再加载,想调用的时候,出现了问题:

神经网络:

class Net(torch.nn.Module):
    def __init__(self):
        super(Net, self).__init__()
        self.conv1 = torch.nn.Conv2d(3, 10, kernel_size=5)
        self.conv2 = torch.nn.Conv2d(10, 20, kernel_size=5)
        self.pooling = torch.nn.MaxPool2d(2)
        self.fc = torch.nn.Linear(2420, 5)
    def forward(self, x):
        # flatten data from (n,1,28,28) to (n, 784)
        batch_size = x.size(0)
        x = F.relu(self.pooling(self.conv1(x)))
        x = F.relu(self.pooling(self.conv2(x)))
        x = x.view(batch_size, -1)  # -1 此处自动算出的是320
        # 这个地方我没有理解的是,为什么需要batch_size放入到计算里面?
        # 按照我的理解,这边弄上,意思就是 我弄成64行,然后其它的,随便算了;
        x = self.fc(x)
        return x

然后我保存了下来:

torch.save(Net,'net_params.pth')

之后我去调用这个神经网络,调用的代码如下:

model = torch.load("net_params.pth")
test_image_dir = './3753920123_c7ebc18ee3.jpg'
image_test = Image.open(test_image_dir)
# image.show()
transfrom_image = torchvision.transforms.Compose([torchvision.transforms.Resize([56, 56]),
                                                  torchvision.transforms.ToTensor()])
image_test = transfrom_image(image_test)
image_test = torch.reshape(image_test, (1, 3, 56, 56))
outputs_imgae = model(image_test)
print(outputs_imgae)

报错内容如下:

AttributeError: Can't get attribute 'Net' on <module '__main__' from 'E:/xjustudy/pythonproj/jhcproj3/test-001/test_001.py'>

看到这个还是挺懵逼的,幸好看了《PyTorch深度学习快速入门教程(绝对通俗易懂!)【小土堆】》

解决的办法是,将之前编好的神经网络给复制到相同的文件夹里面,更改后的代码如下:

import torch
import torchvision
from PIL import Image
import torch.nn.functional as F
class Net(torch.nn.Module):
    def __init__(self):
        super(Net, self).__init__()
        self.conv1 = torch.nn.Conv2d(3, 10, kernel_size=5)
        self.conv2 = torch.nn.Conv2d(10, 20, kernel_size=5)
        self.pooling = torch.nn.MaxPool2d(2)
        self.fc = torch.nn.Linear(2420, 5)
    def forward(self, x):
        # flatten data from (n,1,28,28) to (n, 784)
        batch_size = x.size(0)
        x = F.relu(self.pooling(self.conv1(x)))
        x = F.relu(self.pooling(self.conv2(x)))
        x = x.view(batch_size, -1)  # -1 此处自动算出的是320
        # 这个地方我没有理解的是,为什么需要batch_size放入到计算里面?
        # 按照我的理解,这边弄上,意思就是 我弄成64行,然后其它的,随便算了;
        x = self.fc(x)
        return x
model = torch.load("net_params.pth")
test_image_dir = './3753920123_c7ebc18ee3.jpg'
image_test = Image.open(test_image_dir)
# image.show()
transfrom_image = torchvision.transforms.Compose([torchvision.transforms.Resize([56, 56]),
                                                  torchvision.transforms.ToTensor()])
image_test = transfrom_image(image_test)