了解一个简单的 LSTM pytorch

Understanding a simple LSTM pytorch

import torch,ipdb
import torch.autograd as autograd
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
from torch.autograd import Variable

rnn = nn.LSTM(input_size=10, hidden_size=20, num_layers=2)
input = Variable(torch.randn(5, 3, 10))
h0 = Variable(torch.randn(2, 3, 20))
c0 = Variable(torch.randn(2, 3, 20))
output, hn = rnn(input, (h0, c0))

这是文档中的 LSTM 示例。我不知道了解以下内容:

  1. 什么是输出大小,为什么没有在任何地方指定?
  2. 为什么输入有 3 个维度。 5和3代表什么?
  3. h0和c0中的2和3分别代表什么?

编辑:

import torch,ipdb
import torch.autograd as autograd
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
from torch.autograd import Variable
import torch.nn.functional as F

num_layers=3
num_hyperparams=4
batch = 1
hidden_size = 20
rnn = nn.LSTM(input_size=num_hyperparams, hidden_size=hidden_size, num_layers=num_layers)

input = Variable(torch.randn(1, batch, num_hyperparams)) # (seq_len, batch, input_size)
h0 = Variable(torch.randn(num_layers, batch, hidden_size)) # (num_layers, batch, hidden_size)
c0 = Variable(torch.randn(num_layers, batch, hidden_size))
output, hn = rnn(input, (h0, c0))
affine1 = nn.Linear(hidden_size, num_hyperparams)

ipdb.set_trace()
print output.size()
print h0.size()

*** RuntimeError: matrices expected, got 3D, 2D tensors at

LSTM 的输出是最后一层所有隐藏节点的输出。
hidden_size - 每层的 LSTM 块数。
input_size - 每个时间步的输入特征数。
num_layers - 隐藏层数。
总共有 hidden_size * num_layers 个 LSTM 块。

输入维度为(seq_len, batch, input_size)
seq_len - 每个输入流中的时间步数。
batch - 每批输入序列的大小。

隐藏维度和单元格维度为:(num_layers, batch, hidden_size)

output (seq_len, batch, hidden_size * num_directions): tensor containing the output features (h_t) from the last layer of the RNN, for each t.

所以会有hidden_size * num_directions个输出。您没有将 RNN 初始化为双向的,因此 num_directions 为 1。因此 output_size = hidden_size.

编辑:您可以使用线性层更改输出数量:

out_rnn, hn = rnn(input, (h0, c0))
lin = nn.Linear(hidden_size, output_size)
v1 = nn.View(seq_len*batch, hidden_size)
v2 = nn.View(seq_len, batch, output_size)
output = v2(lin(v1(out_rnn)))

注意:对于这个答案,我假设我们只是在谈论非双向 LSTM。

来源:PyTorch docs.

你可以设置

batch_first = True

如果你想将输入和输出提供为

(batch_size, seq, input_size)

今天才知道,分享给大家

cdo256 的回答几乎是正确的。他在提到 hidden_size 的意思时弄错了。他解释为:

hidden_size - 每层 LSTM 块的数量。

但实际上,这里有一个更好的解释:

单元格中的每个sigmoid、tanh或隐藏状态层实际上是一组节点,其数量等于隐藏层大小。因此,LSTM 单元中的每个“节点”实际上是一组正常的神经网络节点,就像在密集连接的神经网络的每一层中一样。 因此,如果您设置 hidden_size = 10,那么您的每个 LSTM 块或单元将具有包含 10 个节点的神经网络。 您的 LSTM 模型中的 LSTM 块总数将等于您的序列长度。

这个可以通过分析nn.LSTM和nn.LSTMCell:

中例子的区别看出

https://pytorch.org/docs/stable/nn.html#torch.nn.LSTM

https://pytorch.org/docs/stable/nn.html#torch.nn.LSTMCell