您的位置:首页 > 房产 > 家装 > 02_TensorFlow2 Eager Execution:让AI编程从‘慢条斯理’变‘急不可耐’的神奇魔法!

02_TensorFlow2 Eager Execution:让AI编程从‘慢条斯理’变‘急不可耐’的神奇魔法!

2024/10/6 6:02:40 来源:https://blog.csdn.net/luorongxi123/article/details/141437400  浏览:    关键词:02_TensorFlow2 Eager Execution:让AI编程从‘慢条斯理’变‘急不可耐’的神奇魔法!

在这里插入图片描述

1. Eager execution 的特性

即刻执行(Eager execution)是TensorFlow2.0的新特性,如同python解释器一样,执行即可获得计算结果,不需要手动建立图结构和会话,与python的兼容性更强, 为快速搭建和测试算法模型提供了便利。

2. 特性介绍

tensorflow 2.0 默认是 Eager execution 模式

eager 模式对 numpy 的支持很友好,具体如下:

  • numpy 的操作可以接受 Tensor 作为参数
  • Tensorflow 的数学操作会将 Python 对象和 Numpy 的 arrays 转换成 Tensor
  • tf.Tensor.numpy 方法返回 numpy 的 ndarry

可逐行动态控制流,逐行控制代码的运行

一切皆函数,无须手动搭建 tensorflow 数据结构

3. 相关API

3.1 即刻输出

# 导入Tensorflow
import tensorflow as tf
# 创建张量
scalar_tf = tf.constant(3.14)
# 执行操作
m = tf.add(scalar_tf, scalar_tf)
# 输出操作结果
m
<tf.Tensor: shape=(), dtype=float32, numpy=6.28>

3.2 状态查看和启动

默认情况下,Eager execution处于启用状态,可以用tf.executing_eargerly()查看Eager Execution当前的启动状态,返回True则是开启,False是关闭。可以用tf.compat.v1.enable_eager_execution()启动eager模式。

# 查看Eager Execution当前的启动状态
tf.executing_eagerly()
True

3.4 关闭与启动 eager 模式

关闭 eager 模式的函数是 tf.compat.v1.disable_eager_ececution()

启动 eager 模式的函数是 tf.compat.v1.enable_eager_execution()

# 默认是开启的,先关闭
tf.compat.v1.disable_eager_execution()
# 查看状态
tf.compat.v1.executing_eagerly()
False
# 开启 eager 模式
tf.compat.v1.enable_eager_execution()
# 查看状态
tf.compat.v1.executing_eagerly()
True

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com