我正在处理不同长度的序列。但我只想根据序列末尾计算的输出对它们进行评分。
样本经过排序,长度逐渐减小,并且用零填充。对于 5 个 1D 样本,它看起来像这样(为了可见性省略了宽度尺寸):
array([[5, 7, 7, 4, 5, 8, 6, 9, 7, 9],
[6, 4, 2, 2, 6, 5, 4, 2, 2, 0],
[4, 6, 2, 4, 5, 1, 3, 1, 0, 0],
[8, 8, 3, 7, 7, 7, 9, 0, 0, 0],
[3, 2, 7, 5, 7, 0, 0, 0, 0, 0]])
对于 LSTM,我使用 nn.utils.rnn.pack_padded_sequence
以及各个序列长度:
x = nn.utils.rnn.pack_padded_sequence(x, [10, 9, 8, 7, 5], batch_first=True)
模型构造函数中LSTM的初始化:
self.lstm = nn.LSTM(width, n_hidden, 2)
然后我调用 LSTM 并解压缩值:
x, _ = self.lstm(x)
x = nn.utils.rnn.pad_packed_sequence(x1, batch_first=True)
然后我应用全连接层和 softmax
x = x.contiguous()
x = x.view(-1, n_hidden)
x = self.linear(x)
x = x.reshape(batch_size, n_labels, 10) # 10 is the sample height
return F.softmax(x, dim=1)
这给了我一个形状为batch x n_labels x height
(5x12x10)的输出。
对于每个样本,我只想对最后一个输出batch x n_labels
(5*12) 使用一个分数。我的问题是我怎样才能实现这一目标?
一个想法是对从模型返回的最后一个隐藏层应用tanh
,但我不太确定这是否会产生相同的结果。是否可以有效地提取在序列末尾计算的输出,例如使用与 pack_padded_sequence
相同长度的序列?
最佳答案
正如 Neaabfi 回答的那样,hidden[-1]
是正确的。为了更具体地回答您的问题,如 docs写道:
output, (h_n, c_n) = self.lstm(x_pack) # batch_first = True
# h_n is a vector of shape (num_layers * num_directions, batch, hidden_size)
在你的例子中,你有一个由 2 个 LSTM 层组成的堆栈,只有前向
方向,那么:
h_n shape is (num_layers, batch, hidden_size)
也许,您可能更喜欢最后一层的隐藏状态h_n
,那么**这是您应该做的:
output, (h_n, c_n) = self.lstm(x_pack)
h = h_n[-1] # h of shape (batch, hidden_size)
y = self.linear(h)
Here是将任何循环层 LSTM
、RNN
或 GRU
包装到 DynamicRNN
中的代码。 DynamicRNN
能够对不同长度的序列执行循环计算,而无需关心长度的顺序。
关于python - Pytorch LSTM grad 仅在最后一个输出上,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55907234/