简体   繁体   English

"图形模式下的 tf.gradients() 与 tf.gradientTape.gradient()"

[英]tf.gradients() vs tf.gradientTape.gradient() in graph mode

I had a question regarding the behavior of tf.gradients() as opposed tf.gradientTape.gradient() in graph mode.我有一个关于 tf.gradients() 而不是 tf.gradientTape.gradient() 在图形模式下的行为的问题。

Given a differentiable function y = f(x), where x and y are each single tensorflow tensors, is there any difference between the behavior of tf.gradient(y, x) vs tape.gradient(y, x) where tape is an instance of tf.gradientTape (assuming the use of graph mode) ?给定一个可微函数 y = f(x),其中 x 和 y 都是单个张量流张量,tf.gradient(y, x) 与 tape.gradient(y, x) 的行为之间有什么区别,其中 tape 是一个tf.gradientTape 的实例(假设使用图形模式)?

Not sure why tensorflow has two different gradient methods which can be used with graph mode - maybe there are some subtle differences in the implementations?不知道为什么 tensorflow 有两种不同的梯度方法可以与图形模式一起使用 - 也许实现中有一些细微的差异? I've looked at the documentation for gradientTape and tf.gradients but it's not clear whether there is any difference between the behavior of these methods for a single (x, y) pair, or whether it's just that tf.gradients() can be used in this case for a speedup when using graph mode.我查看了 gradientTape 和 tf.gradients 的文档,但不清楚这些方法对于单个 (x, y) 对的行为是否有任何区别,或者是否只是 tf.gradients() 可以在这种情况下用于加速使用图形模式。

Thank you so much for your help!非常感谢你的帮助!

"

TF.gradients<\/strong> TF.gradients<\/strong>

tf.gradients<\/code> is only valid in a graph context. tf.gradients<\/code>仅在图形上下文中有效。 In particular, it is valid in the context of a tf.function<\/code> wrapper, where code is executing as a graph.特别是,它在tf.function<\/code>包装器的上下文中有效,其中代码作为图形执行。

@tf.function
def example():
  a = tf.constant(0.)
  b = 2 * a
  return tf.gradients(a + b, [a, b], stop_gradients=[a, b])
example()

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

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