【发布时间】:2021-08-11 21:50:28
【问题描述】:
我尝试使用torch.nn.LSTM 实现一个两层双向 LSTM。
我做了一个玩具示例:一批 3 个张量,它们完全相同(请参阅下面的代码)。我希望 BiLSTM 的输出在批处理维度上是相同的,即out[:,0,:] == out[:,1,:] == out[:, 2, :]。
但似乎并非如此。根据我的实验,有 20%~40% 的时间,输出是不一样的。所以我想知道我哪里弄错了。
# Python 3.6.6, Pytorch 0.4.1
import torch
def test(hidden_size, in_size):
seq_len, batch = 4, 3
bilstm = torch.nn.LSTM(input_size=in_size, hidden_size=hidden_size,
num_layers=2, bidirectional=True)
# create a batch with 3 exactly the same tensors
a = torch.rand(seq_len, 1, in_size) # (seq_len, 1, in_size)
x = torch.cat((a, a, a), dim=1)
out, _ = bilstm(x) # (seq_len, batch, n_direction * hidden_size)
# expect the output should be the same along the batch dimension
assert torch.equal(out[:, 0, :], out[:, 1, :])
assert torch.equal(out[:, 1, :], out[:, 2, :])
if __name__ == '__main__':
count, total = 0, 0
for h_size in range(1, 51):
for in_size in range(1, 51):
total += 1
try:
test(h_size, in_size)
except AssertionError:
count += 1
print('percentage of assertion error:', count / total)
【问题讨论】: