我从这个github得到的编码器的输出有一些不一致之处。
编码器看起来如下:
class Encoder(nn.Module):
r"""Applies a multi-layer LSTM to an variable length input sequence.
"""
def __init__(self, input_size, hidden_size, num_layers,
dropout=0.0, bidirectional=True, rnn_type='lstm'):
super(Encoder, self).__init__()
self.input_size = 40
self.hidden_size = 512
self.num_layers = 8
self.bidirectional = True
self.rnn_type = 'lstm'
self.dropout = 0.0
if self.rnn_type == 'lstm':
self.rnn = nn.LSTM(input_size, hidden_size, num_layers,
batch_first=True,
dropout=dropout,
bidirectional=bidirectional)
def forward(self, padded_input, input_lengths):
"""
Args:
padded_input: N x T x D
input_lengths: N
Returns: output, hidden
- **output**: N x T x H
- **hidden**: (num_layers * num_directions) x N x H
"""
total_length = padded_input.size(1) # get the max sequence length
packed_input = pack_padded_sequence(padded_input, input_lengths,
batch_first=True,enforce_sorted=False)
packed_output, hidden = self.rnn(packed_input)
pdb.set_trace()
output, _ = pad_packed_sequence(packed_output, batch_first=True, total_length=total_length)
return output, hidden所以它只包含一个rnn单元,如果我打印编码器,这是输出:
LSTM(40, 512, num_layers=8, batch_first=True, bidirectional=True)所以它应该有一个512大小的输出,对吗?但是当我给一个张量的大小为torch.Size([16, 1025, 40])的张量时,我从这个神经网络得到的输出有一个新的编码大小为1024 torch.Size([16, 1025, 1024]),当它应该被编码到512的时候,它应该是1025个矢量样本,大小为40 (这是为了适应RNN而打包的)。
我遗漏了什么东西吗?
发布于 2020-05-12 11:42:53
设置bidirectional=True使LSTM双向,这意味着将有两个LSTM,一个从左到右,另一个从右到左。
来自文件-产出
torch.nn.utils.rnn.PackedSequence作为输入,输出也将是一个填充序列。
对于未包装的情况,可以使用output.view(seq_len, batch, num_directions, hidden_size)分离方向,正向和后向分别为方向0和1。同样,方向可以在包装箱中分开。您的输出具有大小为[batch, seq_len, 2 * hidden_size] (在您的情况下,由于设置了batch_first=True)的batch和seq_len,这是因为使用了双向的LSTM。将两者的输出连接起来,以便获得两者的信息,如果您想要对它们进行不同的处理,则可以很容易地将它们分开。
https://stackoverflow.com/questions/61748181
复制相似问题