我在這里遵循 Tensorflow 函式指南,根據我的理解,TF 將跟蹤并為每次呼叫具有不同輸入簽名(即資料型別和輸入形狀)的函式創建一個圖形。然而,下面的例子讓我感到困惑。由于兩個輸入都是整數并且具有完全相同的形狀,因此 TF 不應該只執行一次跟蹤和構建圖形嗎?為什么在呼叫函式時兩次都會發生跟蹤?
@tf.function
def a_function_with_python_side_effect(x):
print("Tracing!") # An eager-only side effect.
return x * x tf.constant(2)
# This retraces each time the Python argument changes,
# as a Python argument could be an epoch count or other
# hyperparameter.
print(a_function_with_python_side_effect(2))
print(a_function_with_python_side_effect(3))
輸出:
Tracing!
tf.Tensor(6, shape=(), dtype=int32)
Tracing!
tf.Tensor(11, shape=(), dtype=int32)
uj5u.com熱心網友回復:
數字 2 和 3 被視為不同的整數值,這就是您看到“跟蹤!”的原因。兩次。您所指的行為:“TF 將跟蹤并為每次呼叫具有不同輸入簽名(即資料型別和輸入形狀)的函式創建一個圖形”適用于張量而不是簡單的數字。您可以通過將兩個數字轉換為張量常量來驗證:
import tensorflow as tf
@tf.function
def a_function_with_python_side_effect(x):
print("Tracing!") # An eager-only side effect.
return x * x tf.constant(2)
print(a_function_with_python_side_effect(tf.constant(2)))
print(a_function_with_python_side_effect(tf.constant(3)))
Tracing!
tf.Tensor(6, shape=(), dtype=int32)
tf.Tensor(11, shape=(), dtype=int32)
這是混合 python 標量和tf.function. 在此處查看跟蹤規則。在那里你讀到:
為 tf.Tensor 生成的快取鍵是它的形狀和資料型別。
為 Python 原語(如 int、float、str)生成的快取鍵是它的值。
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/391936.html
