我正在Python中使用TensorFlow2.0中的GradientTape()和jacobian()。你知道吗
此代码执行良好:
x = tf.Variable(2.0, dtype=tf.float32)
with tf.GradientTape() as gT:
gT.watch(x)
g = tf.convert_to_tensor([x, 0.0], dtype=tf.float32)
dg = gT.jacobian(g, x)
但这条代码打破了:
x = tf.Variable(2.0, dtype=tf.float32)
with tf.GradientTape() as gT:
gT.watch(x)
gv = tf.Variable([x, 0.0], dtype=tf.float32)
g = tf.convert_to_tensor(gv , dtype=tf.float32)
dg = gT.jacobian(g, x)
并抛出错误:
InvalidArgumentError: You must feed a value for placeholder tensor 'loop_body/Placeholder' with dtype int32 [[node loop_body/Placeholder (defined at ...Anaconda3\lib\site-packages\tensorflow_core\python\framework\ops.py:1751) ]] [Op:__inference_f_995]
Traceback (most recent call last) ipython-input-32-686c8a0d6e95 in module
4 gv = tf.Variable([x, 0.0], dtype=tf.float32)
5 g = tf.convert_to_tensor(gv , dtype=tf.float32)
----> 6 dg = gT.jacobian(g, x)
为什么第一个代码有效,而第二个代码无效?你知道吗
原因很简单
在第一个例子中,你得到
g = tf.convert_to_tensor([x, 0.0], dtype=tf.float32)
计算
dg/dx
和g
与x
有直接关系,工作正常。你知道吗但在第二个例子中
在
g
和x
之间已经没有联系了,因为当你打电话的时候gv = tf.Variable([x, 0.0], dtype=tf.float32)
它只是复制
x
中的值,并且不携带对x
的引用,因此您无法获得dg/dx
的导数。但如果你尝试dg/d(gv)
,它会奏效的。你知道吗PS:但是我没有收到错误(对于您的第二个示例)。我刚得到
None
。你知道吗相关问题 更多 >
编程相关推荐