我正在使用Google Colab,当我运行以下代码时:
from torch import tensor, arange
print( arange(0.0, 1.2, 0.2) )
print( arange(tensor(0.0), tensor(1.2), tensor(0.2)) )我得到了输出:
tensor([0.0000, 0.2000, 0.4000, 0.6000, 0.8000, 1.0000])
tensor([0.0000, 0.2000, 0.4000, 0.6000, 0.8000, 1.0000, 1.2000])这种差异在arange(0.0,1.1,0.1)中也会发生,但在arange(0.0,1.5,0.5)中没有差异。
为什么看似相似的代码会产生不同的结果,我如何预测这种情况何时会发生?
发布于 2021-09-15 00:33:11
这是一个数值精度问题:(
默认情况下,Python以双精度(也称为float64)存储浮点数,而PyTorch默认使用float32。
如果你尝试:
tensor(1.2).item()
tensor(1.2).dtype # torch.float32您将获得1.2000000476837158,并且具有该数字的arange将不同于具有1.2的数字。在这种特定情况下,如果您尝试:
import torch
from torch import tensor, arange
print(arange(tensor(0.0), tensor(1.2, dtype=torch.float64), tensor(0.2)))你会得到你想要的,但是即使是float64最终也会有一些精度问题。无论如何,因为Python也使用双精度,所以在这种情况下来回转换标量不会有问题。
我不确定你能不能预见到。
https://stackoverflow.com/questions/69185671
复制相似问题