在Tensorflow 2.0中使用GradientTape()和jacobian()时发生错误

问题描述 投票:0回答:1

我正在使用Python的Tensorflow 2.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:您必须使用dtype int32为占位符张量'loop_body / Placeholder'提供一个值[[节点loop_body /占位符(在... Anaconda3 \ lib \ site-packages \ tensorflow_core \ python \ framework \ ops.py:1751处定义)]] [操作:__ inference_f_995]

追踪(最近一次通话最近)模块中的ipython-input-32-686c8a0d6e954 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)

为什么第一个代码有效,但是第二个代码无效?

python tensorflow tensorflow2.0 gradienttape
1个回答
0
投票
原因很简单,

在第一个示例中,您得到了

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

© www.soinside.com 2019 - 2024. All rights reserved.