简体   繁体   English

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

[英]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?我发现tensorflowpytorch 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
  • tensorflow == 2.5.0 tensorflow == 2.5.0
  • torch == 1.9.0手电筒 == 1.9.0

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.

相关问题 使用tanh作为张量流中MNIST数据集中的激活函数 - using tanh as activation function in MNIST dataset in tensorflow 自定义激活 tensorflow 中的 function 与 tanh 的可学习参数 - Custom Activation function in tensorflow with learnable parameter for tanh 与 numpy 相比,Tensorflow 中的 tanh function 的精度更高 - Higher accuracy for tanh function in Tensorflow as compare to numpy 为什么 Pytorch 和 Tensorflow 中交叉熵的实现不同? - Why is the implementation of cross entropy different in Pytorch and Tensorflow? 为什么Tensorflow和Pytorch的mse结果不一样? - Why the results in mse are different between Tensorflow and Pytorch? 在tensorflow和pytorch中看到的collect()函数的不同行为 - Different behavior of gather() function as seen in tensorflow and pytorch 为什么tensorflow和keras SimpleRNN图层默认激活tanh - Why do tensorflow and keras SimpleRNN layers have a default activation of tanh 为什么 tensorflow 中的 tanh 梯度是 `grad = dy * (1 - y*y)` - Why gradient of tanh in tensorflow is `grad = dy * (1 - y*y)` 具有量化值的Tensorflow tanh - Tensorflow tanh with quantized values 为什么 Tensorflow 和 Pytorch CrossEntropy 损失对同一示例返回不同的值 - Why is the Tensorflow and Pytorch CrossEntropy loss returns different values for same example
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM