RNN中的隐藏大小与输入大小

2024-04-19 02:34:34 发布

您现在位置:Python中文网/ 问答频道 /正文

前提1:

关于RNN层中的神经元,我的理解是,“在每个时间步,每个神经元都接收来自上一时间步y(t–1)的输入向量x(t)和输出向量”[1]

https://github.com/ebolotin6/ebolotin6.github.io/blob/master/images/rnn.png

前提2:

我还了解到,在Pythorch的GRU层中,输入大小隐藏的大小意味着:

  • input_size – The number of expected features in the input x
  • hidden_size – The number of features in the hidden state h

因此,自然地,隐藏的大小应该代表GRU层中神经元的数量。在

我的问题:

考虑到以下GRU层:

# assume that hidden_size = 3

class Encoder(nn.Module):
    def __init__(self, src_dictionary_size, hidden_size):
        super(Encoder, self).__init__()
        self.embedding = nn.Embedding(src_dictionary_size, hidden_size)
        self.gru = nn.GRU(input_size = hidden_size, hidden_size = hidden_size)

假设一个隐藏的大小为3,我的理解是上面的GRU层将有3个神经元,每个神经元在每个时间步同时接受一个大小为3的输入向量。在

我的问题是:为什么隐藏的input_size的参数必须相等?一、 为什么3个神经元都不能接受一个5大小的输入向量?在

例如:以下两种产品尺寸不匹配:

^{pr2}$

[1]杰伦,奥瑞莲。使用Scikit Learn和TensorFlow进行实际操作的机器学习(第388页)。奥莱利传媒。Kindle版。在

[3]https://pytorch.org/docs/stable/nn.html#torch.nn.GRU


添加再现性的完整代码:

^{3}$

Tags: oftheinselfnumberinputsize时间
1条回答
网友
1楼 · 发布于 2024-04-19 02:34:34

我刚刚解决了这个问题,这个错误是自己造成的。在

结论:输入大小隐藏的大小可以不同,这没有固有的问题。问题中的前提陈述正确。在

上面的(完整)代码的问题是GRU的初始隐藏状态没有正确的维度。初始隐藏状态必须与后续隐藏状态具有相同的维度。在我的例子中,初始隐藏状态的形状是(1,2,5)而不是(1,2,4)。前者,5代表嵌入向量的维数。4表示GRU中隐藏的_大小(num neurons)。正确代码如下:

import torch
import torch.nn as nn

class Encoder(nn.Module):
    def __init__(self, src_dictionary_size, input_size, hidden_size):
        super(Encoder, self).__init__()
        self.hidden_size = hidden_size
        self.embedding = nn.Embedding(src_dictionary_size, input_size)
        self.gru = nn.GRU(input_size = input_size, hidden_size = hidden_size)

    def forward(self, pad_seqs, seq_lengths, hidden):
        """
        Args:
          pad_seqs of shape (max_seq_length, batch_size, 1): Padded source sequences.
          seq_lengths: List of sequence lengths.
          hidden of shape (1, batch_size, hidden_size): Initial states of the GRU.

        Returns:
          outputs of shape (max_seq_length, batch_size, hidden_size): Padded outputs of GRU at every step.
          hidden of shape (1, batch_size, hidden_size): Updated states of the GRU.
        """
        embedded_sqs = self.embedding(pad_seqs).squeeze(2)
        packed_sqs = pack_padded_sequence(embedded_sqs, seq_lengths)
        packed_output, h_n = self.gru(packed_sqs, hidden)
        output, input_sizes = pad_packed_sequence(packed_output)

        return output, h_n

    def init_hidden(self, batch_size=1):
        return torch.zeros(1, batch_size, self.hidden_size)

def test_Encoder_shapes():
    hidden_size = 4
    embedding_size = 5
    encoder = Encoder(src_dictionary_size=5, input_size = embedding_size, hidden_size = hidden_size)
    print(encoder)

    max_seq_length = 4
    batch_size = 2
    hidden = encoder.init_hidden(batch_size=batch_size)
    pad_seqs = torch.tensor([
        [1, 2],
        [2, 3],
        [3, 0],
        [4, 0]
    ]).view(max_seq_length, batch_size, 1)

    outputs, new_hidden = encoder.forward(pad_seqs=pad_seqs, seq_lengths=[4, 2], hidden=hidden)
    assert outputs.shape == torch.Size([4, batch_size, hidden_size]), f"Bad outputs.shape: {outputs.shape}"
    assert new_hidden.shape == torch.Size([1, batch_size, hidden_size]), f"Bad new_hidden.shape: {new_hidden.shape}"
    print('Success')

test_Encoder_shapes()

相关问题 更多 >