Python ``tensorflow.GradientTape()`` 梯度带自动求导与高阶导数实例


发布日期 : 2019-12-03 11:53:14 UTC

访问量: 10 次浏览

Python – tensorflow.GradientTape()

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

GradientTape()是用来记录自动区分的操作。

语法:
tensorflow.GradientTape( persistent, watch_accessed_variables)

参数:

  • persistent(可选):它可以是True或False,默认值为False。它定义了是否创建持久的梯度带。
  • watch\_accessed\_variables : 这是一个布尔值,定义磁带是否会在磁带激活时自动监视任何(可训练的)变量。

示例 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)