[英]Why tanh function return different in tensorflow and pytorch?
I find that tensorflow
and pytorch
tanh
result is different, I want to know why did this happen?我发现
tensorflow
和pytorch
tanh
结果不同,我想知道为什么会这样? I know that the difference is very small, so is this acceptable?我知道差异很小,所以这可以接受吗?
import numpy as np
import tensorflow as tf
import torch
np.random.seed(123)
tf.random.set_seed(123)
torch.manual_seed(123)
batch, sentence_length, embedding_dim = 20, 5, 10
value = np.random.random((batch, sentence_length, embedding_dim)).astype("f")
value = value * 10
tf_x = tf.constant(value, dtype=tf.float32)
tf_out = tf.math.tanh(tf_x)
pt_x = torch.from_numpy(value)
pt_out = torch.tanh(pt_x)
print((tf_out.numpy() == pt_out.numpy()).all()) # return False
print(((tf_out.numpy() - pt_out.numpy()) < 1e-6).all()) # return True
Running your code with the following line at the end:最后使用以下行运行代码:
print(np.allclose(tf_out.numpy(), pt_out.numpy())) # Returns True
You will receive True
.您将收到
True
。 I do not know exactly how tensorflow and pytorch compute the tanh oppeartion, but when working with floating points, you rarely are exactely equal.我不知道 tensorflow 和 pytorch 是如何计算 tanh oppeartion 的,但是在处理浮点数时,你很少会完全相等。 However, you should be receiving equal results up to a certain tolerance, which is exactly what
np.allclose()
checks.但是,您应该在一定公差范围内收到相同的结果,这正是
np.allclose()
检查的内容。 Read more onallclose here 在这里阅读更多关于allclose
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.