繁体   English   中英

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

[英]Why tanh function return different in tensorflow and pytorch?

我发现tensorflowpytorch 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
  • 手电筒 == 1.9.0

最后使用以下行运行代码:

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM