为什么 tanh 函数在 tensorflow 和 pytorch 中返回不同?

原文标题Why tanh function return different in tensorflow and pytorch?

我发现tensorflow和pytorch tanh结果不一样,想知道为什么会这样?我知道差别很小,那么这样可以接受吗?

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
  • tensorflow == 2.5.0
  • pytorch == 1.9.0

原文链接:https://stackoverflow.com//questions/71446623/why-tanh-function-return-different-in-tensorflow-and-pytorch

回复

我来回复
  • Tomer Geva的头像
    Tomer Geva 评论

    在末尾使用以下行运行您的代码:

    print(np.allclose(tf_out.numpy(), pt_out.numpy()))  # Returns True
    

    您将收到 True 。我不确切知道 tensorflow 和 pytorch 如何计算 tanh oppeartion,但是在使用浮点数时,您很少完全相等。但是,您应该在一定的公差范围内收到相等的结果,这正是np.allclose() 检查。在此处阅读更多关于allclose

    2年前 0条评论