【问题标题】:How to set the output size of an RNN?如何设置RNN的输出大小?
【发布时间】:2019-08-24 23:23:08
【问题描述】:

我想要一个输入大小为 7、隐藏大小为 10、输出大小为 2 的 RNN。 因此,对于形状 99x1x7 的输入,我期望形状为 99x1x2 的输出。 仅对于 RNN,我得到:

model = nn.RNN(input_size=7, hidden_size=10, num_layers=1)

output,hn=model(torch.rand(99,1,7))
print(output.shape) #torch.Size([99, 1, 10])
print(hn.shape)     #torch.Size([ 1, 1, 10])

所以我假设我仍然需要在它后面加上Linear

model = nn.Sequential(nn.RNN(input_size=7, hidden_size=10, num_layers=1),
                      nn.Linear(in_features=10, out_features=2))
model(torch.rand(99,1,7))

Traceback (most recent call last):
  File "train_rnn.py", line 80, in <module>
    main()
  File "train_rnn.py", line 25, in main
    model(torch.rand(99,1,7))
  File "/home/.../virtual-env/lib/python3.6/site-packages/torch/nn/modules/module.py", line 493, in __call__
    result = self.forward(*input, **kwargs)
  File "/home/.../virtual-env/lib/python3.6/site-packages/torch/nn/modules/container.py", line 92, in forward
    input = module(input)
  File "/home/.../virtual-env/lib/python3.6/site-packages/torch/nn/modules/module.py", line 493, in __call__
    result = self.forward(*input, **kwargs)
  File "/home/.../virtual-env/lib/python3.6/site-packages/torch/nn/modules/linear.py", line 92, in forward
    return F.linear(input, self.weight, self.bias)
  File "/home/.../virtual-env/lib/python3.6/site-packages/torch/nn/functional.py", line 1404, in linear
    if input.dim() == 2 and bias is not None:
AttributeError: 'tuple' object has no attribute 'dim'

我猜这是因为Linear 接收到RNN.forward 产生的元组。但是我应该如何将两者结合起来呢?

【问题讨论】:

    标签: python pytorch recurrent-neural-network


    【解决方案1】:

    来自 pytorch 文档https://pytorch.org/docs/stable/nn.html?highlight=rnn#torch.nn.RNN

    输出的形状为seq_len, batch, num_directions * hidden_size

    因此,根据您的需要,您可以添加一个 fc 层以获得大小为 2 的输出。 基本上,Sequential 将在 next_one 的输出之上应用每个模型,因此您不能使用 Sequential 或创建一个适用于序列的特殊线性层,以下应该可以工作:

    class seq_Linear(nn.module):
      def __init__(self, linear):
        self.linear = linear
      # To apply on every hidden state
      def forward(self, x):
        return torch.stack([self.linear(hs) for hs in x])
      # To apply on the last hidden state
      def forward(self, x):
        return self.linear(x[-1])
    

    并在您的代码中用 seq_Linear(nn.Linear) 替换您的 nn.Linear。

    编辑:如果你想创建一个大小为 2 的输出序列,也许最好的方法是在你的第一个 RNN 之上堆叠另一个 RNN,其中 input_size 10 和 output_size 2,它们应该可以堆叠在 Sequential 中没有任何麻烦。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2022-09-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-10-30
      • 2021-08-13
      • 2010-12-12
      相关资源
      最近更新 更多