Pytorch 求和问题(可能是浮点问题)
我有一个简单的Python测试,目的是计算一个列表中几个项目的总和,然后把这个列表放到一个torch张量里:
lst = [0.0014, -0.0306, 0.0005, 0.0011, 0.0012, 0.0022, 0.0017, 0.0011,
0.0017, 0.0011, 0.0012, 0.0017, 0.0014, 0.0015, 0.0010, 0.0006,
0.0006, 0.0004, 0.0009, 0.0007, 0.0008, 0.0007, 0.0013, 0.0013,
0.0015, 0.0023, 0.0006]
LEN=27
trch = torch.Tensor([lst])
print('--------------------------------------------------------------')
print(trch.sum(1, keepdim=True))
print(sum(lst))
print(trch @ torch.ones((LEN,1)))
print(torch.mm( trch , torch.ones((LEN,1))))
trch_sum= 0
for num in lst:
trch_sum += num
print(trch_sum)
我得到了以下(合理的)结果:
tensor([[-0.0001]])
-9.999999999999912e-05
tensor([[-9.9999e-05]])
tensor([[-9.9999e-05]])
-9.999999999999972e-05
不过,把列表中的最后一个数字改成0.0007后,结果就大大改变了。
tensor([[-9.3132e-10]])
9.215718466126788e-19
tensor([[1.1642e-09]])
tensor([[1.1642e-09]])
3.2526065174565133e-19
我知道这是浮点数的问题,但有没有办法改善这个情况呢?
1 个回答
0
这是一个数字精度的问题。
当你用 lst
创建一个torch张量时,里面的数值会自动变成fp32格式,这样会导致精度下降。如果你想提高精度,可以明确地把张量设置为fp64格式,但即使这样,结果还是会有一些差异。
lst = [0.0014, -0.0306, 0.0005, 0.0011, 0.0012, 0.0022, 0.0017, 0.0011,
0.0017, 0.0011, 0.0012, 0.0017, 0.0014, 0.0015, 0.0010, 0.0006,
0.0006, 0.0004, 0.0009, 0.0007, 0.0008, 0.0007, 0.0013, 0.0013,
0.0015, 0.0023, 0.0007]
x = torch.tensor([lst], dtype=torch.float64)
x.sum()
> 2.6020852139652106e-18
sum(lst)
> 3.2526065174565133e-19
(x @ torch.ones(x.shape[::-1], dtype=torch.float64)).item()
> 3.2526065174565133e-19
(x @ torch.ones(x.shape, dtype=torch.float64).T).item()
> 2.4936649967166602e-18