繁体   English   中英

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

[英]Error when working with GradientTape() and jacobian() in Tensorflow 2.0

我正在 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 [[node loop_body/Placeholder(定义于 ...Anaconda3\\lib\\site-packages\\tensorflow_core\\python\\framework\\ops.py:1751)为占位符张量“loop_body/Placeholder”提供一个值]] [操作:__inference_f_995]

模块中的回溯(最近一次调用) ipython-input-32-686c8a0d6e95
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/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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM