【问题标题】:Compute gradient of the ouputs wrt the weights计算权重的输出梯度
【发布时间】:2020-04-03 20:09:35
【问题描述】:

从张量流模型开始,我希望能够检索输出相对于权重的梯度。反向传播旨在计算权重的损失梯度,为了在代码中的某处计算权重的输出梯度。

但我想知道如何在 API 级别获得这个雅可比行列式,有什么想法吗?

我知道我们可以访问磁带,但我不确定如何处理它,实际上我不需要整个雅可比行列式我只需要能够计算 J^{*} 的矩阵向量积v 其中 J^{} 是给定向量的 jacobian 和 va 的转置。

谢谢你, 问候。

【问题讨论】:

  • 我不确定您到底想做什么,但在 TensorFlow 2.0 中,您可以使用渐变磁带获取 gradient,它为您提供每个源值的聚合渐变(例如Jacobian 矩阵中的每一列),或jacobian,它实际上为您提供了 Jacobian 矩阵。

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


【解决方案1】:

如果您只需要计算向量-雅可比积,那么只做这将比计算完整的雅可比要高效得多。计算 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]

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-08-14
    • 1970-01-01
    • 2015-05-09
    • 2019-09-24
    • 2020-05-12
    • 1970-01-01
    • 2021-04-01
    • 1970-01-01
    相关资源
    最近更新 更多