📜  Python – tensorflow.GradientTape.watch()

📅  最后修改于: 2022-05-13 01:54:24.586000             🧑  作者: Mango

Python – tensorflow.GradientTape.watch()

TensorFlow 是由 Google 设计的开源Python库,用于开发机器学习模型和深度学习神经网络。

watch()用于通过 Tape 开始跟踪张量。

示例 1:

Python3
# 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)


Python3
# 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)


输出:

res:  tf.Tensor(8.0, shape=(), dtype=float32)

示例 2:

Python3

# 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)