TensorFlow是Google設計的開源Python庫,用於開發機器學習模型和深度學習神經網絡。
GradientTape()用於記錄自動區分的操作。
用法:tensorflow.GradientTape( persistent, watch_accessed_variables)
參數:
- persistent(optional):它可以是True或False,默認值為False。它定義是否創建持久漸變磁帶。
- watch_accessed_variables:這是一個布爾值,用於定義在磁帶處於活動狀態時磁帶是否將自動監視任何(可訓練的)變量。
範例1:
Python3
# Importing the library
import tensorflow as tf
x = tf.constant(4.0)
# Using GradientTape
with tf.GradientTape() as gfg:
gfg.watch(x)
y = x * x * x
# Computing gradient
res = gfg.gradient(y, x)
# Printing result
print("res:",res)
輸出:
res: tf.Tensor(48.0, shape=(), dtype=float32)
範例2:
Python3
# Importing the library
import tensorflow as tf
x = tf.constant(4.0)
# Using GradientTape
with tf.GradientTape() as gfg:
gfg.watch(x)
# Using nested GradientTape for calculating higher order derivative
with tf.GradientTape() as gg:
gg.watch(x)
y = x * x * x
# Computing first order gradient
first_order = gg.gradient(y, x)
# Computing Second order gradient
second_order = gfg.gradient(first_order, x)
# Printing result
print("first_order:",first_order)
print("second_order:",second_order)
輸出:
first_order: tf.Tensor(48.0, shape=(), dtype=float32) second_order: tf.Tensor(24.0, shape=(), dtype=float32)
相關用法
注:本文由純淨天空篩選整理自aman neekhara大神的英文原創作品 Python – tensorflow.GradientTape()。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。