代码之家  ›  专栏  ›  技术社区  ›  rawwar

用前馈网络在Pythoch中建立递归神经网络

  •  1
  • rawwar  · 技术社区  · 7 年前

    我正在经历 this 辅导的。我有一个关于以下课程代码的问题:

    class RNN(nn.Module):
        def __init__(self, input_size, hidden_size, output_size):
            super(RNN, self).__init__()
    
            self.input_size = input_size
            self.hidden_size = hidden_size
            self.output_size = output_size
    
            self.i2h = nn.Linear(input_size + hidden_size, hidden_size)
            self.i2o = nn.Linear(input_size + hidden_size, output_size)
            self.softmax = nn.LogSoftmax()
    
        def forward(self, input, hidden):
            combined = torch.cat((input, hidden), 1)
            hidden = self.i2h(combined)
            output = self.i2o(combined)
            output = self.softmax(output)
            return output, hidden
    
        def init_hidden(self):
            return Variable(torch.zeros(1, self.hidden_size))
    

    此代码取自 Here . 有人提到

    由于网络的状态保存在图中,而不是图层中,所以您可以简单地创建一个nn.linear,并反复使用它以进行重复。

    我不明白的是,怎样才能只增加输入特征的大小,在nn.linear,并说它是一个RNN。我这里缺什么?

    1 回复  |  直到 6 年前
        1
  •  2
  •   M. Deckers    7 年前

    网络是经常性的,因为您在示例中评估了多个时间步骤。 以下代码也取自 pytorch tutorial you linked to .

    loss_fn = nn.MSELoss()
    
    batch_size = 10
    TIMESTEPS = 5
    
    # Create some fake data
    batch = torch.randn(batch_size, 50)
    hidden = torch.zeros(batch_size, 20)
    target = torch.zeros(batch_size, 10)
    loss = 0
    for t in range(TIMESTEPS):
        # yes! you can reuse the same network several times,
        # sum up the losses, and call backward!
        hidden, output = rnn(batch, hidden)
        loss += loss_fn(output, target)
    loss.backward()
    

    因此,网络本身不是循环的,但是在这个循环中,您可以将它作为循环的网络,通过多次将前一步的隐藏状态与批输入一起提供。

    您还可以通过在每个步骤中反向传播丢失并忽略隐藏状态来非重复使用它。

    由于网络的状态保存在图中,而不是图层中,所以您可以简单地创建一个nn.linear,并反复使用它以进行重复。

    这意味着,计算梯度的信息不包含在模型本身中,因此您可以将模块的多个评估附加到图中,然后通过整个图进行反向传播。 这在本教程的前几段中进行了描述。