gpt4 book ai didi

python - Tensorflow中 `tf.function`和 `autograph.to_graph`是什么关系?

转载 作者:太空宇宙 更新时间:2023-11-04 09:26:14 27 4
gpt4 key购买 nike

通过 tf.functionautograph.to_graph 可以获得类似的结果。
然而,这似乎与版本有关。

例如函数(摘自官方指南):

def square_if_positive(x):
if x > 0:
x = x * x
else:
x = 0.0
return x

可以使用以下方法在图形模式下进行评估:

  • autograph.to_graph TF 1.14
tf_square_if_positive = autograph.to_graph(square_if_positive)

with tf.Graph().as_default():
g_out = tf_square_if_positive(tf.constant( 9.0))
with tf.Session() as sess:
print(sess.run(g_out))
  • tf.function TF2.0
@tf.function
def square_if_positive(x):
if x > 0:
x = x * x
else:
x = 0.0
return x

square_if_positive(tf.constant( 9.0))

所以:

  • tf.functionautograph.to_graph 之间有什么关系?可以假设 tf.function 在内部使用 autograph.to_graph(以及 autograph.to_code),但这远非显而易见。
  • TF2.0 是否仍支持 autograph.to_graph 片段(因为它需要 tf.Session)?它存在于 autograph doc 中在 TF 1.14 中,但在 TF 2.0 的相应文档中没有

最佳答案

我在一篇分为三部分的文章中涵盖并回答了您的所有问题:“分析 tf.function 以发现 AutoGraph 的优势和微妙之处”:part 1 , part 2 , part 3 .

总结并回答您的 3 个问题:

  • tf.functionautograph.to_graph 有什么关系?

tf.function 默认使用 AutoGraph。当您第一次调用 tf.function 修饰的函数时会发生什么:

  1. 函数体被执行(在 TensorFlow 1.x 中,因此没有急切模式)并跟踪其执行(现在 tf.function 知道存在哪些节点,if 的哪个分支到保持等等)
  2. 同时,AutoGraph 启动并尝试转换为 tf.* 调用,它知道的 Python 语句 (while -> tf.while, if -> tf.cond, ...)-.

合并第 1 点和第 2 点的信息,构建一个新图,并根据函数名称和参数类型将其缓存在 map 中(请参阅文章以获得更好的理解)。

  • TF2.0 是否仍支持 autograph.to_graph 代码段?

是的,tf.autograph.to_graph仍然存在,它会在内部为您创建一个 session (在 TF2 中您不必担心它们)。

无论如何,我建议您阅读链接的三篇文章,因为它们详细介绍了 tf.function 的这一点和其他特点。

关于python - Tensorflow中 `tf.function`和 `autograph.to_graph`是什么关系?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57526164/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com