【问题标题】:How to change the structure of a model in PyTorch如何在 PyTorch 中更改模型的结构
【发布时间】:2021-03-12 21:15:56
【问题描述】:

我想构建一个堆叠的自动编码器或递归网络。这些是构建动态神经网络所必需的,它可以在每次迭代中改变其结构。

比如我先训练

class Net(nn.Module):
    def __init__(self):
        super(Net, self).__init__()
        self.fc1 = nn.Linear(784,500)
        self.fc2 = nn.Linear(500,784)

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

接下来,我想使用之前的 fc1 和 fc2 进行训练

class Net(nn.Module):
    def __init__(self):
        super(Net, self).__init__()
        self.fc1 = nn.Linear(784,500)
        self.fc3 = nn.Linear(500,10)        
        self.fc4 = nn.Linear(10,500)
        self.fc2 = nn.Linear(500,784)

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

如何在单一模型中构建这些网络?

【问题讨论】:

  • 你能详细说明一下吗?你到底想要什么?例如,即时创建新图层?您可以在 forward 方法中使用一个简单的 for 循环来执行此操作,该循环取决于输入 x

标签: python neural-network deep-learning pytorch


【解决方案1】:

您可以简单地为您的 forward 函数添加一个参数,它可以在您想要的两种可能性之间切换:

class Net(nn.Module):
def __init__(self):
    super(Net, self).__init__()
    self.fc1 = nn.Linear(784,500)
    self.fc3 = nn.Linear(500,10)        
    self.fc4 = nn.Linear(10,500)
    self.fc2 = nn.Linear(500,784)

def forward(self, x, n_layers=2):
    if 2 == n_layers:
        x = F.relu(self.fc1(x))
        x = F.relu(self.fc2(x))
        return x
    elif 4 == n_layers:
        x = F.relu(self.fc1(x))
        x = F.relu(self.fc3(x))
        x = F.relu(self.fc4(x))
        x = F.relu(self.fc2(x))
        return x
    else:
        raise Exception("Not implemented")

【讨论】:

  • 这些将使 NN 只剩下两个(无论编程多少个)选项。我认为,这个问题与自动神经架构搜索有关。如果有人知道如何允许 NN 添加没有此类固定和显式声明的节点和层,请添加到这些=) 非常有兴趣了解如何在 PyTorch 中实现它。
猜你喜欢
  • 2022-11-17
  • 1970-01-01
  • 1970-01-01
  • 2017-07-17
  • 2023-02-20
  • 1970-01-01
  • 1970-01-01
  • 2018-06-03
相关资源
最近更新 更多