tensorflow--AutoGraph:将 Python 控制流转换为 TensorFlow 计算图

使用 tf.autograph 模块的低层 API tf.autograph.to_code 将函数 square_if_positive 转换成 TensorFlow 计算图:

import tensorflow as tf

# @tf.function 使用名为 AutoGraph 的机制将函数中的 Python 控制流语句转换成 TensorFlow 计算图中的对应节点。
# 以下是一个示例,使用 tf.autograph 模块的低层 API tf.autograph.to_code 将函数 square_if_positive 转换成 TensorFlow 计算图
@tf.function
def square_if_positive(x):
    if x > 0:
        x = x * x
    else:
        x = 0
    return x

a = tf.constant(1)
b = tf.constant(-1)
print(square_if_positive(a), square_if_positive(b))
# AutoGraph 起到了类似编译器的作用,能够帮助我们通过更加自然的 Python 控制流轻松地构建带有条件 / 循环的计算图,
# 而无需手动使用 TensorFlow 的 API 进行构建。
print(tf.autograph.to_code(square_if_positive.python_function))

原文:
https://blog.csdn.net/nanke_4869/article/details/114220354

猜你喜欢

转载自blog.csdn.net/fgg1234567890/article/details/115190438