Python – tensorflow.GradientTape.watch()
TensorFlow是谷歌设计的开源Python库,用于开发机器学习模型和深度学习神经网络。
watch()是用来开始追踪Tape的Tensor的。
语法: watch( tensor )
参数:
- tensor :它是一个张量或要观察的张量列表。
返回值: None
抛出:
- ValueError:如果传递的参数不是张量,它将引发ValueError。
示例 1:
# Importing the library
import tensorflow as tf
x = tf.constant(4.0)
# Using GradientTape
with tf.GradientTape() as gfg:
# Starting the recording x
gfg.watch(x)
y = x * x
# Computing gradient
res = gfg.gradient(y, x)
# Printing result
print("res: ", res)
输出:
res: tf.Tensor(8.0, shape=(), dtype=float32)
示例 2:
# Importing the library
import tensorflow as tf
x = tf.constant(4.0)
z = tf.constant(5.0)
# Using GradientTape
with tf.GradientTape(persistent = True) as gfg:
# Starting the recording x and z
gfg.watch([x, z])
y = z * z
u = x * x
# Computing gradient
grad_y = gfg.gradient(y, z)
grad_u = gfg.gradient(u, x)
# Printing result
print("grad_y: ", grad_y)
print("grad_u: ", grad_u)
输出:
grad_y: tf.Tensor(10.0, shape=(), dtype=float32)
grad_u: tf.Tensor(8.0, shape=(), dtype=float32)