![](/img/trans.png)
[英]How is the output h_n of an RNN (nn.LSTM, nn.GRU, etc.) in PyTorch structured?
[英]PyTorch: nn.LSTM output different results for the same inputs in the same batch
我尝试使用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)
使您困惑的是浮点精度。 浮点运算有些不准确,并且可能相差很小。请改用以下方法:
torch.set_default_dtype(torch.float64)
然后,您将看到它们在批处理暗处应该是相同的。
感谢您纠正一些英语语法错误。
我对GRU
有同样的问题,以下为我解决了这个问题。
在测试之前设置手动种子并将模型设置为评估模式:
torch.manual_seed(42)
bilstm.eval() # or: bilstm.train(false)
此外,我必须在每次调用模型之前(在测试期间)设置相同的种子。 在你的情况下:
torch.manual_seed(42)
out, _ = bilstm(x) # (seq_len, batch, n_direction * hidden_size)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.