【问题标题】:PyTorch: nn.LSTM output different results for the same inputs in the same batchPyTorch:nn.LSTM 在同一批次中为相同的输入输出不同的结果
【发布时间】: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)

【问题讨论】:

    标签: python lstm pytorch


    【解决方案1】:

    让您感到困惑的是浮点精度。浮点运算稍微不准确,可能相差很小 改用这个:

    torch.set_default_dtype(torch.float64) 
    

    然后您会看到它们在批次昏暗中应该是相同的。

    感谢您纠正一些英语语法错误。

    【讨论】:

      【解决方案2】:

      GRU 我也遇到了同样的问题,下面为我解决了这个问题。
      在测试之前设置手动种子并将模型设置为评估模式:

      torch.manual_seed(42)
      bilstm.eval()  # or: bilstm.train(false)
      

      来源: LSTMcell and LSTM returning different outputs

      此外,我必须在每次调用模型之前(在测试期间)设置相同的种子。在你的情况下:

      torch.manual_seed(42)
      out, _ = bilstm(x)  # (seq_len, batch, n_direction * hidden_size)
      

      【讨论】:

        猜你喜欢
        • 2022-10-13
        • 1970-01-01
        • 2016-08-14
        • 1970-01-01
        • 2013-06-06
        • 1970-01-01
        • 2012-09-08
        • 1970-01-01
        • 2021-09-03
        相关资源
        最近更新 更多