Neural network 在Pytorch中如何以神经网络的深度为参数构造网络

Neural network 在Pytorch中如何以神经网络的深度为参数构造网络,neural-network,pytorch,Neural Network,Pytorch,我编写了以下代码,将网络深度作为Pytorch中的参数。 后来我意识到,即使我使用了许多隐藏层,可学习的参数仍然保持不变 class Net3(torch.nn.Module): def __init__(self, n_feature, n_hidden, n_output, depth, init): super(Net3, self).__init__() self.input = torch.nn.Linear(n_feature, n_hidde

我编写了以下代码,将网络深度作为Pytorch中的参数。 后来我意识到,即使我使用了许多隐藏层,可学习的参数仍然保持不变

class Net3(torch.nn.Module):
    def __init__(self, n_feature, n_hidden, n_output, depth, init):
        super(Net3, self).__init__()
        self.input = torch.nn.Linear(n_feature, n_hidden).float().to(device)   
        self.hidden = torch.nn.Linear(n_hidden, n_hidden).float().to(device)   
        self.predict = torch.nn.Linear(n_hidden, n_output).float().to(device)   =
        self.depth = depth 


    def forward(self, x):
        x = F.relu(self.input(x))      # activation function for hidden layer
        for i in range(self.depth):
           x = F.relu(self.hidden(x))      # activation function for hidden layer
        x = self.predict(x)           
        return x

有没有其他方法可以做到这一点

在init中,您需要创建多个隐藏层,目前只创建一个。使用torch.nn.ModuleDict可以在很少开销的情况下完成此操作,它将为您提供命名层:

class Net3(torch.nn.Module):
    def __init__(self, n_feature, n_hidden, n_output, depth, init):
        super(Net3, self).__init__()
        self.layers = nn.ModuleDict() # a collection that will hold your layers

        self.layers['input'] = torch.nn.Linear(n_feature, n_hidden).float().to(device)

        for i in range(1, depth):
            self.layers['hidden_'+str(i)] = torch.nn.Linear(n_hidden, n_hidden).float().to(device)  

        self.layers['output'] = torch.nn.Linear(n_hidden, n_output).float().to(device)   =
        self.depth = depth 


    def forward(self, x):
        for layer in self.layers:
            x = F.relu(self.layers[layer](x))

        return x

仅供参考:我上面的实现也将relu应用于输出层,但您应该能够自己解决这个问题。您可以决定在向前传球中应用激活,如上所述,并确保每个层都有正确的激活。另一种可能是使用nn.ReLU而不是F.ReLU将激活添加到self.layers本身