0

我正在尝试比较 Android、Tensorflow 和 Pytorch 上的浮点数。我观察到的是,我在 Tensorflow 和 Android 上得到了相同的结果,但在 Pytorch 上却不同,因为 Android 和 Tensorflow 正在执行舍入操作。请看以下结果:

TensorFlow

import tensorflow as tf
a=tf.convert_to_tensor(np.array([0.9764764, 0.79078835, 0.93181187]), dtype=tf.float32)

session = tf.Session()
result = session.run(a*a*a*a)

print(result) 

PyTorch

import torch as th

th.set_printoptions(precision=8)

a=th.from_numpy(np.array([0.9764764, 0.79078835, 0.93181187])).type(th.FloatTensor)

result = a*a*a*a


print(result)

安卓:

for (index in 0 until a.size) {
   var res = a[index] * a[index] * a[index] * a[index]
   result.add(res)
}

print("r=$result")

结果如下:

Android:           [0.9091739,  0.3910579,  0.7538986]
TensorFlow:        [0.9091739,  0.3910579,  0.7538986]
PyTorch:           [0.90917391, 0.39105791, 0.75389862]

你可以看到 PyTorch 的值是不同的。我知道在这个例子中这种影响很小,但是当我们进行训练时,并且我们以不同的批次和 epoch 运行 1000 轮,这种差异可能会累积并显示出不理想的结果。谁能指出我们如何修复在三个平台上具有相同的数字。

谢谢。

4

1 回答 1

1

您在打印时没有使用相同级别的精度,因此会得到不同的结果。在内部,这些结果是相同的,它只是一个工件,你看到由于 python 的默认设置在逗号后只打印 7 位数字。

如果我们在 numpy 中设置的精度与在 PyTorch 中设置的精度相同,我们会得到:

import numpy as np
import tensorflow as tf

# setting the print precision of numpy to 8 like in your pytorch example
np.set_printoptions(precision=8, floatmode="fixed")

a=tf.convert_to_tensor(np.array([0.9764764, 0.79078835, 0.93181187]), dtype=tf.float32)

session = tf.Session()
result = session.run(a*a*a*a)
print(result)

结果是:

[0.90917391 0.39105791 0.75389862]

与 PyTorch 中的完全相同。

于 2021-02-26T15:58:24.040 回答