Python ``tensorflow.grad_pass_through()`` 函数用法详解


发布日期 : 2021-07-12 14:05:37 UTC

访问量: 10 次浏览

Python – tensorflow.grad\_pass\_through()

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

grad_pass_through()
用于创建 grad-pass-through 操作,通过函数的前向行为传递。

语法:
tensorflow.grad_passs_through( f )

参数:

  • f:它是一个返回张量或张量嵌套结构的函数。

返回:
它返回一个函数h(x),该函数返回与f(x)相同的值,其梯度与身份函数的梯度相同。

示例 1:

# Importing the library
import tensorflow as tf

# Initializing the Tensor
x = tf.Variable(2.0, name ="x")
z = tf.Variable(4.0, name ="z")

with tf.GradientTape() as gfg:
  # y will evaluate to 16.0 i.e 4**2
  y = tf.grad_pass_through(x.assign)(z**2)

# res will evaluate to 8.0
res = gfg.gradient(y, z)

# Printing result
print("y: ", y)
print("res: ", res)

输出:

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

示例 2:

# Importing the library
import tensorflow as tf

# Initializing the Tensor
x = tf.Variable(3.0, name ="x")

with tf.GradientTape() as gfg:
  # y will evaluate to 9.0 i.e 3**2
  y = tf.grad_pass_through(x.assign)(x**2)

# res will evaluate to 6.0
res = gfg.gradient(y, x)

# Printing result
print("y: ", y)
print("res: ", res)

输出:

y: tf.Tensor(9.0, shape=(), dtype=float32)
res: tf.Tensor(6.0, shape=(), dtype=float32)