如果您只需要计算向量-雅可比积,那么只做这将比计算完整的雅可比要高效得多。计算 N 个变量的函数的 Jacobian 将花费 O(N) 时间,而向量-Jacobian 乘积需要 O(1) 时间。
那么,如何在 TensorFlow 中计算向量雅可比积?诀窍是在gradient 函数中使用output_gradients 关键字arg。您将output_gradients 的值设置为向量-雅可比积中的向量。让我们看一个例子。
import tensorflow as tf
with tf.GradientTape() as g:
x = tf.constant([1.0, 2.0])
g.watch(x)
y = x*x # y is a length 2 vector
vec = tf.constant([2.0,3.0]) # vector in vector jacobian product
grad = g.gradient(y,x,output_gradients = vec)
print(grad) # prints the vector-jacobian product, [4.,12.]
注意:如果您尝试在未设置 output_gradients 的情况下在 tensorflow 中计算向量值(而不是标量)函数的梯度,它会计算向量设置为全 1 的向量雅可比积。例如,
import tensorflow as tf
with tf.GradientTape() as g:
x = tf.constant([1.0, 2.0])
g.watch(x)
y = x*x # y is a length 2 vector
grad = g.gradient(y,x)
print(grad) # prints the vector-jacobian product with a vector of ones, [2.0,4.0]