tf.GradientTape是可以记录Tensorflow中自动微分的操作,如果计算操作在tf.GradientTape下执行,并且至少有一个输入被“监视”,那么该操作就会被记录。使用方法:
import tensorflow as tf
x = tf.Variable(0.0, dtype=tf.float32) # 变量Variable将会被自动“监视”
# 常量
a = tf.constant(1.0, dtype=tf.float32)
b = tf.constant(-2.0, dtype=tf.float32)
c = tf.constant(1.0, dtype=tf.float32)
with tf.GradientTape() as tape:
tape.watch([c]) # 手动使用watch函数监视常量c
y = a*tf.pow(x, 2)+b*x+c # 函数f(x) = a*x**2 + b*x + c
dy_dx, dy_dc = tape.gradient(y, [x, c]) # 求f(x)关于x=0,c=1的导数
print(dy_dx, dy_dc)
# 输出 tf.Tensor(-2.0, shape=(), dtype=float32) tf.Tensor(1.0, shape=(), dtype=float32)
与优化器配合求函数的最小值
import tensorflow as tf
x = tf.Variable(0.0, dtype=tf.float32)
a = tf.constant(1.0, dtype=tf.float32)
b = tf.constant(-2.0, dtype=tf.float32)
c = tf.constant(1.0, dtype=tf.float32)
optimizer = tf.keras.optimizers.SGD(learning_rate=0.01)
for _ in tf.range(1000):
with tf.GradientTape() as tape:
y = a*tf.pow(x, 2)+b*x+c
dy_dx=tape.gradient(y,x)
optimizer.apply_gradients(grads_and_vars=[(dy_dx, x)])
tf.print("y =", y, "; x =", x)
# 输出 y = 0 ; x = 0.999998569
tf.keras.optimizers.SGD()会返回一个随机梯度下降优化器,这里我们令其学习率a = 0.01,优化器的apply_gradients函数将会将梯度应用到变量上,令变量值朝着梯度方向改变。
本文详细介绍TensorFlow中tf.GradientTape的使用方法,包括如何记录自动微分操作,求导数,以及与优化器结合求函数最小值的过程。
2360

被折叠的 条评论
为什么被折叠?



