Python TensorFlow ``GradientTape.gradient()`` 方法与梯度计算实例


发布日期 : 2022-11-24 16:20:26 UTC

访问量: 10 次浏览

Python – tensorflow.GradientTape.gradient()

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

gradient()是用来计算梯度的,使用的操作记录在本带的上下文中。

语法:
gradient(target, sources, output_gradients, unconnected_gradients)

参数:

  • target:它是张量或张量的列表,要进行区分。
  • sources: 它是张量或张量的列表。目标值是针对源头进行区分的。
  • output\_gradients: 它是一个梯度的列表,默认值为None。
  • unconnected\_gradients: 它的值可以是无或零,默认值为无。

返回:它返回一个列表或Tensor的嵌套结构。

示例 1:

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

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