为何两种nn.LSTM调用方式会产生不同结果?
问题:两种LSTM调用方式输出结果不一致的原因?
参数说明:
- 12:序列长度(seq_len)
- 20:多预测数(muti-prediction)
- 7:样本组数
- 64:隐藏层大小(hidden_size)
我采用两种方式调用PyTorch的LSTM:一种将20*7合并为批量维度进行计算,另一种通过Python循环逐一生成7组结果,但最终输出的out1和out2用==比较时出现大量False,请问为何两者不相等?
测试代码
import torch as t lstm = t.nn.LSTM(input_size=64, hidden_size=64, num_layers=1, bias=True, batch_first=False, dropout=0, bidirectional=False) a = t.randn(12, 20, 7, 64) hn = t.randn(1, 20, 7, 64) cn = t.randn(1, 20, 7, 64) # 方式1:合并20*7为批量维度 out1, _ = lstm(a.reshape(12, 20 * 7, 64), (hn.reshape(1, 20 * 7, 64), cn.reshape(1, 20 * 7, 64))) out1 = out1.reshape(12, 20, 7, 64) # 方式2:循环逐组计算 out2 = [] for n in range(7): out_tmp, _ = lstm(a[:, :, n], (hn[:, :, n], cn[:, :, n])) out2.append(out_tmp) out2 = t.stack(out2, dim=2) print(out1 == out2) # 输出大量False
原因分析
- 浮点数计算精度差异:两种方式的计算逻辑在数学上是等价的,但并行计算(合并批量)和循环串行计算中,浮点数的运算顺序、舍入处理存在细微差别,会产生极小的数值误差(通常在
1e-6量级)。 - 严格相等判断的局限性:直接用
==比较张量是严格相等判断,哪怕是极小的精度误差都会返回False。正确的做法是使用允许误差范围的比较方法:
print(t.allclose(out1, out2, atol=1e-6)) # 通常会输出True,验证两者数值近似等价
内容的提问来源于stack exchange,提问作者rising_sun
相关产品推荐
相关产品推荐

