TensorFlow2.0教程-AutoGraph

Tensorflow 2.0 教程持续更新 https://blog.csdn.net/qq_31456593/article/details/88606284

TensorFlow 2.0 教程- Keras 快速入门
TensorFlow 2.0 教程-keras 函数api
TensorFlow 2.0 教程-使用keras训练模型
TensorFlow 2.0 教程-用keras构建自己的网络层
TensorFlow 2.0 教程-keras模型保存和序列化
TensorFlow 2.0 教程-eager模式
TensorFlow 2.0 教程-Variables
TensorFlow 2.0 教程–AutoGraph

TensorFlow 2.0 深度学习实践

TensorFlow2.0 教程-图像分类
TensorFlow2.0 教程-文本分类
TensorFlow2.0 教程-过拟合和欠拟合

完整tensorflow2.0教程代码请看tensorflow2.0:中文教程tensorflow2_tutorials_chinese(欢迎star)

更多TensorFlow 2.0 入门教程请持续关注博客:https://blog.csdn.net/qq_31456593/article/details/88606284

TensorFlow2.0教程-AutoGraph

tf.function的一个很酷的新功能是AutoGraph,它允许使用自然的Python语法编写图形代码。

1.tf.function装饰器

当使用tf.function注释函数时,可以像调用任何其他函数一样调用它。
它将被编译成图,这意味着可以获得更快执行,更好地在GPU或TPU上运行或导出到SavedModel。

@tf.function
def simple_nn_layer(x, y):
    return tf.nn.relu(tf.matmul(x, y))


x = tf.random.uniform((3, 3))
y = tf.random.uniform((3, 3))

simple_nn_layer(x, y)
<tf.Tensor: id=25, shape=(3, 3), dtype=float32, numpy=
array([[0.75023645, 0.19047515, 0.10737072],
       [1.1521267 , 0.49491584, 0.19416495],
       [0.5541876 , 0.24642248, 0.09543521]], dtype=float32)>

如果我们检查注释的结果,我们可以看到它是一个特殊的可调用函数,它处理与TensorFlow运行时的所有交互。

simple_nn_layer
<tensorflow.python.eager.def_function.Function at 0x7ff5e164eb38>

如果代码使用多个函数,则无需对它们进行全部注释

  • 从带注释函数调用的任何函数也将以图形模式运行。
def linear_layer(x):
    return 2 * x + 1


@tf.function
def deep_net(x):
    return tf.nn.relu(linear_layer(x))


deep_net(tf.constant((1, 2, 3)))
<tf.Tensor: id=39, shape=(3,), dtype=int32, numpy=array([3, 5, 7], dtype=int32)>

2.使用Python控制流程

在tf.function中使用依赖于数据的控制流时,可以使用Python控制流语句,AutoGraph会将它们转换为适当的TensorFlow操作。 例如,如果语句依赖于Tensor,则语句将转换为tf.cond()。

@tf.function
def square_if_positive(x):
  if x > 0:
    x = x * x
  else:
    x = 0
  return x


print('square_if_positive(2) = {}'.format
  • 3
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值