【发布时间】:2022-01-04 03:47:39
【问题描述】:
我试图在以下代码中了解TF GRADIENT TAPE 的用途:
import tensorflow as tf
var = tf.Variable(5.0)
with tf.GradientTape() as tape:
op = (2*var)+(var*var)
diff = tape.gradient(op,var)
print (diff)
操作:
diff = tf.Tensor(12.0, shape=(), dtype=float32)
我很困惑,因为var=5,op=(2*5)+(5*5)=>35,如果我是calculating the derivative of a constant,那么diff should be 0
我理解它12 的原因,因为它没有将var 视为5 而不是(2*var)+(var*var)=> 2var+var**2,因此计算此函数的导数变为2+2*var=>12。
但我不明白的是,为什么不考虑给var 的值?
【问题讨论】:
-
抱歉,不考虑为
var提供的值是什么意思?梯度2+2*var显然是var的函数。 -
@rchome 如果在
tape中考虑了var的给定值,那么导数应该是0对吧? -
var是一个变量,而不是一个常量。在这种情况下,op相对于var的导数是 12。如果您改为使用var = tf.constant(5.0),您将获得None用于渐变,因为GradientTape不是“观看”var。 tensorflow.org/guide/autodiff#controlling_what_the_tape_watches
标签: tensorflow keras tensorflow2.0 gradient-descent gradienttape