[英]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
最后使用以下行運行代碼:
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.