TensorFlow是Google設計的開源Python庫,用於開發機器學習模型和深度學習神經網絡。
gradient()用於使用在此磁帶上下文中記錄的操作來計算梯度。
用法:gradient(target, sources, output_gradients, unconnected_gradients)
參數:
- target:它是Tensor或要區分的Tensor列表。
- sources:它是Tensor或Tensor列表。目標值與來源有所區別。
- output_gradients:它是漸變列表,默認值為“無”。
- unconnected_gradients:它的值可以為無或為零,默認值為無。
返回值:它返回Tensor的列表或嵌套結構。
範例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.gradient()。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。