【问题标题】:How do i add an layer to an Nural network in pytorch如何在 pytorch 中向神经网络添加图层
【发布时间】:2019-06-01 09:58:52
【问题描述】:

我想通过编程向 Nural 网络添加一个层,它返回了这个错误TypeError: forward() missing 1 required positional argument: 'x'

class Net(nn.Module):


    def __init__(self):
        super(Net, self).__init__()

        self.fc1 = nn.Linear(1, 120)
        self.fc2 = nn.Linear(120, 84)
        self.fc3 = nn.Linear(84, 10)

    def forward(self, x):
        x = F.relu(self.fc1(x))
        x = F.relu(self.fc2(x))
        x = self.fc3(x)
        return x

    def num_flat_features(self, x):
        size = x.size()[1:]  
        num_features = 1
        for s in size:
            num_features *= s
        return num_features


netz =Net()
print(netz)



netz = nn.Sequential([nn.Linear(10, 120), netz()])



print(netz)
`

当我用netz=torch.load()加载它时发生了同样的错误

似乎导致错误的行是:netz = nn.Sequential([nn.Linear(10, 120), netz()])

如何让它发挥作用?

【问题讨论】:

    标签: python-3.x pytorch


    【解决方案1】:

    好的,有几件事。

    从你为什么调用netz()开始,你已经用netz =Net()实例化了对象,所以这没有意义。

    第二件事,nn.Sequential 期望 *args 作为“构造函数”参数,所以你直接传递模块的子类:netz = nn.Sequential(Net(), nn.Linear(100,100)) 或者你解压它们:nn.Sequential(*[nn.Linear(100,100), Net()])

    您还可以使用 OrderedDict 添加多个模块,这在 PyTorch docs 中有详细记录(您应该顺便咨询一下 - 它的存在是有原因的!

    model = nn.Sequential(OrderedDict([
              ('conv1', nn.Conv2d(1,20,5)),
              ('relu1', nn.ReLU()),
              ('conv2', nn.Conv2d(20,64,5)),
              ('relu2', nn.ReLU())
            ]))
    

    您还可以将带有my_modules.add_module("my_module_name", Net()) 的模块添加到现有的有序模块集合中。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-02-07
      • 2015-10-24
      • 2022-06-22
      • 2021-12-30
      • 2018-12-16
      • 2019-12-10
      • 1970-01-01
      • 2019-04-13
      相关资源
      最近更新 更多