【问题标题】:Building recurrent neural network with feed forward network in pytorch在 pytorch 中使用前馈网络构建循环神经网络
【发布时间】:2018-12-11 15:42:44
【问题描述】:

我正在阅读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。我在这里错过了什么?

【问题讨论】:

    标签: python deep-learning pytorch recurrent-neural-network


    【解决方案1】:

    网络是循环的,因为您在示例中评估了多个时间步。 以下代码也取自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 并一遍又一遍地重复使用它。

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

    【讨论】:

    • 非常感谢您在代码中的评论,这对我有帮助。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-06-04
    • 1970-01-01
    • 1970-01-01
    • 2018-12-16
    • 2017-02-19
    • 2016-11-29
    • 2020-04-16
    相关资源
    最近更新 更多