【发布时间】:2020-06-25 03:32:18
【问题描述】:
背景
在 Tensorflow 2 中,存在一个名为 GradientTape 的类,用于记录对张量的操作,然后可以对结果进行微分并提供给一些最小化算法。比如from the documentation我们有这个例子:
x = tf.constant(3.0)
with tf.GradientTape() as g:
g.watch(x)
y = x * x
dy_dx = g.gradient(y, x) # Will compute to 6.0
gradient 方法的 docstring 意味着第一个参数不仅可以是张量,还可以是张量列表:
def gradient(self,
target,
sources,
output_gradients=None,
unconnected_gradients=UnconnectedGradients.NONE):
"""Computes the gradient using operations recorded in context of this tape.
Args:
target: a list or nested structure of Tensors or Variables to be
differentiated.
sources: a list or nested structure of Tensors or Variables. `target`
will be differentiated against elements in `sources`.
output_gradients: a list of gradients, one for each element of
target. Defaults to None.
unconnected_gradients: a value which can either hold 'none' or 'zero' and
alters the value which will be returned if the target and sources are
unconnected. The possible values and effects are detailed in
'UnconnectedGradients' and it defaults to 'none'.
Returns:
a list or nested structure of Tensors (or IndexedSlices, or None),
one for each element in `sources`. Returned structure is the same as
the structure of `sources`.
Raises:
RuntimeError: if called inside the context of the tape, or if called more
than once on a non-persistent tape.
ValueError: if the target is a variable or if unconnected gradients is
called with an unknown value.
"""
在上面的例子中,很容易看出y,target是要微分的函数,x是取“梯度”的因变量。
根据我有限的经验,gradient 方法似乎返回一个张量列表,sources 的每个元素一个,每个梯度都是一个与 @ 的相应成员形状相同的张量987654332@.
问题
如果target 包含要区分的单个1x1“张量”,则上述gradients 行为的描述是有意义的,因为从数学上讲,梯度向量应该与函数的域具有相同的维度。
但是,如果target 是张量列表,则gradients 的输出仍然是相同的形状。为什么会这样?如果target 被认为是一个函数列表,那么输出不应该类似于雅可比矩阵吗?我该如何从概念上解释这种行为?
【问题讨论】:
标签: python deep-learning neural-network tensorflow2.0