使用 @tf.function 装饰器将 python 函数转换为 tensorflow 图(graph),从而提升执行效率。具体做法是在定义模型逻辑或训练循环的函数前添加该装饰器,这样 tensorflow 会在首次调用时追踪执行路径并构建静态计算图,后续调用直接执行编译后的图代码,避免了 python 解释器的开销和频繁的 eager 模式切换。若输入形状固定且无动态控制流,性能提升最为显著。

@tf.function 对普通数学运算的性能影响如何
对于简单的逐元素数学运算,@tf.function 能显著减少函数调用的开销。通过对比未装饰的 Eager 模式和装饰后的 Graph 模式,可以看到后者在多次重复执行时的平均耗时更低。这是因为 Graph 模式消除了每次调用时的 Python 到 C++ 的边界跨越成本。

import tensorflow as tf
import time
@tf.function
def graph_mode(x, y):
return x + y
def eager_mode(x, y):
return x + y
x = tf.random.uniform([1000, 1000])
y = tf.random.uniform([1000, 1000])
# Warmup
graph_mode(x, y)
eager_mode(x, y)
start = time.time()
for _ in range(100):
graph_mode(x, y)
print(f"Graph: {time.time() - start:.4f}s")
start = time.time()
for _ in range(100):
eager_mode(x, y)
print(f"Eager: {time.time() - start:.4f}s")
如何处理 @tf.function 中的 Python 控制流
当函数中包含 if、for 等 Python 控制流语句时,@tf.function 会将其转换为 TensorFlow 的图结构操作,如 tf.cond 和 tf.while_loop。这允许在图中进行动态分支判断,但需要注意输入类型的变化可能导致重新追踪(Retracing)。为了优化性能,应确保控制流基于 Tensor 而非 Python 标量,或使用 tf.autograph 显式转换。
Nodriver是Undetected-Chromedriver的官方继承者,提供异步浏览器自动化功能,可直接与Chrome DevTools Protocol通信,无需Selenium或WebDriver依赖。专为规避反机器人系统(包括Cloudflare和Imperva)的隐蔽网络自动化而构建。

import tensorflow as tf
@tf.function
def control_flow_example(x):
if x > 0:
return x * 2
else:
return x
print(control_flow_example(tf.constant(5))) # Output: 10
print(control_flow_example(tf.constant(-1))) # Output: -1
输入类型变化导致 @tf.function 重新追踪的影响是什么
当传入 @tf.function 装饰的函数的输入类型或形状发生变化时,TensorFlow 会触发重新追踪(Retracing),即重新构建计算图。这会导致额外的 CPU 开销,尤其是在输入动态变化的场景中。例如,从整数张量变为浮点张量,或从标量变为向量,都会引发重新追踪。为避免此问题,应尽量保持输入签名一致,或使用 input_signature 明确指定输入类型和形状。
Python免费学习笔记(深入):立即使用
在学习笔记中,你将探索 Python 的核心概念和高级技巧!










