计算权重的输出梯度

时间:2019-12-10 15:30:49

标签: tensorflow machine-learning gradient tensorflow2.0 automatic-differentiation

从张量流模型开始,我希望能够检索输出相对于权重的梯度。反向传播的目的是计算权重的损失梯度,以便在代码中的某处执行权重必须发生的输出梯度的计算。

但是我想知道如何在API级别获得这个Jacobian,有什么想法吗?

我知道我们可以使用磁带,但是我不确定该怎么做,实际上我不需要整个雅可比矩阵,我只需要能够计算J ^ {*}的矩阵矢量积 v其中J ^ {}是jacobian和va给定向量的转置。

谢谢你, 问候。

1 个答案:

答案 0 :(得分:0)

如果您只需要计算向量雅可比积,那么这样做比计算完整的雅可比矩阵的效率要高得多。计算N个变量的函数的雅可比行列将花费O(N)时间,而不是矢量-Jacobian乘积的O(1)时间。

那么您如何在TensorFlow中计算向量雅可比积呢?诀窍是在output_gradients函数中使用gradient关键字arg。将output_gradients的值设置为vector-Jacobian乘积中的vector。让我们看一个例子。

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的情况下计算张量流中矢量值(而不是标量)函数的梯度,它将计算矢量-jacobian乘积,其中矢量设置为全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]