tf.py_function 和 tf.function 在目的上有什么区别? [英] What is the difference in purpose between tf.py_function and tf.function?
问题描述
两者之间的区别在我的脑海中模糊不清,尽管有什么是渴望的,什么不是.据我所知,@tf.function
装饰器有两个好处
The difference between the two is muddled in my head, notwithstanding the nuances of what is eager and what isn't. From what I gather, the @tf.function
decorator has two benefits in that
- 它将函数转换为 TensorFlow 图以提高性能,并且
- 通过将许多(但不是全部)常见的 Python 操作解释为张量操作,例如
if
变成tf.cond
等
- it converts functions into TensorFlow graphs for performance, and
- allows for a more Pythonic style of coding by interpreting many (but not all) common-place Python operations into tensor operations, e.g.
if
intotf.cond
, etc.
从 tf.py_function
的定义来看,它似乎只是上面的 #2.因此,当 tf.function
能够提高启动性能并且没有前者无法序列化时,为什么还要使用 tf.py_function
呢?
From the definition of tf.py_function
, it seems that it does just #2 above. Hence, why bother with tf.py_function
when tf.function
does the job with a performance improvement to boot and without the inability of the former to serialize?
推荐答案
随着改进,它们确实开始彼此相似,因此了解它们的来源很有用.最初,不同之处在于:
They do indeed start to resemble each other as they are improved, so it is useful to see where they come from. Initially, the difference was that:
@tf.function
将 python 代码转换为一系列 TensorFlow 图节点.tf.py_function
将现有的 Python 函数包装到单个图形节点中.
@tf.function
turns python code into a series of TensorFlow graph nodes.tf.py_function
wraps an existing python function into a single graph node.
这意味着tf.function
要求你的代码相对简单,而tf.py_function
可以处理任何python代码,无论多么复杂.
This means that tf.function
requires your code to be relatively simple while tf.py_function
can handle any python code, no matter how complex.
虽然这条线确实很模糊,tf.py_function
做了更多的解释,tf.function
接受了很多复杂的 python 命令,但一般规则保持不变:
While this line is indeed blurring, with tf.py_function
doing more interpretation and tf.function
accepting lot's of complex python commands, the general rule stays the same:
- 如果您的 Python 代码逻辑相对简单,请使用
tf.function
. - 当您使用复杂的代码时,例如大型外部库(例如连接到数据库或加载大型外部 NLP 包),请使用
tf.py_function
.
这篇关于tf.py_function 和 tf.function 在目的上有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!