在Tensorflow 2.0中使用GradientTape()和jacobian()时出错

2024-10-02 12:25:17 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在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)

为什么第一个代码有效,而第二个代码无效?你知道吗


Tags: to代码gtconverttfaswithvariable
1条回答
网友
1楼 · 发布于 2024-10-02 12:25:17

原因很简单

在第一个例子中,你得到

g = tf.convert_to_tensor([x, 0.0], dtype=tf.float32)

计算dg/dxgx有直接关系,工作正常。你知道吗

但在第二个例子中

gv = tf.Variable([x, 0.0], dtype=tf.float32)
g = tf.convert_to_tensor(gv , dtype=tf.float32)

gx之间已经没有联系了,因为当你打电话的时候

gv = tf.Variable([x, 0.0], dtype=tf.float32)

它只是复制x中的值,并且不携带对x的引用,因此您无法获得dg/dx的导数。但如果你尝试dg/d(gv),它会奏效的。你知道吗

PS:但是我没有收到错误(对于您的第二个示例)。我刚得到None。你知道吗

相关问题 更多 >

    热门问题