Automatic Differentiation
自动微分是计算函数的导数,这对随机梯度下降(SGD)等算法很有用。
当我们实现神经网络并希望计算输出相对于与一系列函数连接的输入的微分时,它特别有用: L ( x ) = f ( g ( h ( x ) ) ) L(x) = f(g(h(x))) L(x)=f(g(h(x))),微分过程如下:
d L d x = d f d g d g d h d h d x \frac{dL}{dx}=\frac{df}{dg}\frac{dg}{dh}\frac{dh}{dx} dxdL=dgdfdhdgdxdh
这种方式称为链式法则,所以需要计算梯度来进行最终的导数计算。
1. Introduction
一些知识提前说明一下:
- 为了计算梯度,TensorFlow 使用 tf.GradientTape 记录自动微分操作,以便稍后用于梯度计算。
请看下面三个例子
x = tf.constant([2.0])
with tf.GradientTape(persistent=False, watch_accessed_variables=True) as grad:
f = x ** 2
# Print gradient output
print('The gradient df/dx where f=(x^2):\n', grad.gradient(f, x))
# Output
# The gradient df/dx where f=(x^2):
# None
x = tf.constant([2.0])
x = tf.Variable(x)
with tf.GradientTape(persistent=False, watch_accessed_variables=True) as grad:
f = x ** 2
# Print gradient output
print('The gradient df/dx where f=(x^2):\n', grad.gradient(f, x))
# Output
# The gradient df/dx where f=(x^2):
# tf.Tensor([4.], shape=(1,), dtype=float32)
x = tf.constant([2.0])
with tf.GradientTape(persistent=False, watch_accessed_variables=True) as grad:
grad.watch(x)
f = x ** 2
# Print gradient output
print('The gradient df/dx where f=(x^2):\n', grad.gradient(f, x))
# Output
# The gradient df/dx where f=(x^2):
# tf.Tensor([4.], shape=(1,), dtype=float32)
这些例子之间有什么不同呢
- 对原始tensor使用tf.Variable函数使其转化成一个tf.Variable形式
- 使用.watch()操作
关于tensor(张量)和Variable(变量)介绍,请看这里
tf.Variable 将张量转换为变量张量,这是 TensorFlow 推荐的方法。 .watch() 方法确保变量被 tf.GradientTape() 跟踪。
从例子中也可以发现,如果两者都不使用,我们将获得None的结果,因为梯度下降过程没有被任何一方所跟踪
原理其实很简单,就是要不然使用变量获得张量的缓存地址,或者使用watch函数对张量的运行过程进行追踪,不然无法获得张量运算操作之后的地址
一般来说,使用变量以及使用 .watch() 来确保跟踪梯度总是安全的。
我们同时使用了一些默认参数:
- persistent=False:这表明,任何由 tf.GradientTape() 保存的变量,在调用一次梯度后都将被释放
- watch_accessed_variables=True:默认情况下观察变量。所以如果我们有一个变量,我们不需要在这个默认设置下使用 .watch() 。
以下,我们尝试以下将persistent置为True
x = tf.constant([2.0])
x = tf.Variable(x)
# For practice, turn persistent to False to see what happens.
with tf.GradientTape(persistent=True, watch_accessed_variables=True) as grad:
f = x ** 2
h = x ** 3
# Print gradient output
print('The gradient df/dx where f=(x^2):\n', grad.gradient(f, x))
print('The gradient dh/dx where h=(x^3):\n', grad.gradient(h, x))
# Output
'''
The gradient df/dx where f=(x^2):
tf.Tensor([4.], shape=(1,), dtype=float32)
The gradient dh/dx where h=(x^3):
tf.Tensor([12.], shape=(1,), dtype=float32)
'''