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 即刻输出

python 复制代码
# 导入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模式。

python 复制代码
# 查看Eager Execution当前的启动状态
tf.executing_eagerly()
True

3.4 关闭与启动 eager 模式

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

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

python 复制代码
# 默认是开启的,先关闭
tf.compat.v1.disable_eager_execution()
# 查看状态
tf.compat.v1.executing_eagerly()
False
python 复制代码
# 开启 eager 模式
tf.compat.v1.enable_eager_execution()
# 查看状态
tf.compat.v1.executing_eagerly()
True
相关推荐
张人玉8 分钟前
人工智能——猴子摘香蕉问题
人工智能
草莓屁屁我不吃12 分钟前
Siri因ChatGPT-4o升级:我们的个人信息还安全吗?
人工智能·安全·chatgpt·chatgpt-4o
小言从不摸鱼16 分钟前
【AI大模型】ChatGPT模型原理介绍(下)
人工智能·python·深度学习·机器学习·自然语言处理·chatgpt
AI科研视界38 分钟前
ChatGPT+2:修订初始AI安全性和超级智能假设
人工智能·chatgpt
霍格沃兹测试开发学社测试人社区41 分钟前
人工智能 | 基于ChatGPT开发人工智能服务平台
软件测试·人工智能·测试开发·chatgpt
小R资源1 小时前
3款免费的GPT类工具
人工智能·gpt·chatgpt·ai作画·ai模型·国内免费
artificiali4 小时前
Anaconda配置pytorch的基本操作
人工智能·pytorch·python
酱香编程,风雨兼程4 小时前
深度学习——基础知识
人工智能·深度学习
傻傻虎虎4 小时前
【系统架构设计】信息系统基础知识
系统架构
Lossya5 小时前
【机器学习】参数学习的基本概念以及贝叶斯网络的参数学习和马尔可夫随机场的参数学习
人工智能·学习·机器学习·贝叶斯网络·马尔科夫随机场·参数学习