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
相关推荐
蹦蹦跳跳真可爱58920 分钟前
Python----OpenCV(几何变换--图像平移、图像旋转、放射变换、图像缩放、透视变换)
开发语言·人工智能·python·opencv·计算机视觉
蹦蹦跳跳真可爱58924 分钟前
Python----循环神经网络(Transformer ----Layer-Normalization(层归一化))
人工智能·python·rnn·transformer
夜阳朔29 分钟前
Conda环境激活失效问题
人工智能·后端·python
小Lu的开源日常33 分钟前
AI模型太多太乱?用 OpenRouter,一个接口全搞定!
人工智能·llm·api
mit6.8242 小时前
[Meetily后端框架] Whisper转录服务器 | 后端服务管理脚本
c++·人工智能·后端·python
Baihai IDP2 小时前
AI 系统架构的演进:LLM → RAG → AI Workflow → AI Agent
人工智能·ai·系统架构·llm·agent·rag·白海科技
大咖分享课2 小时前
如何设计一个登录管理系统:单点登录系统架构设计
系统架构·sso·登录系统
沫儿笙2 小时前
弧焊机器人气体全方位节能指南
网络·人工智能·机器人
LONGZETECH2 小时前
【龙泽科技】新能源汽车维护与动力蓄电池检测仿真教学软件【吉利几何G6】
人工智能·科技·汽车·汽车仿真教学软件·汽车教学软件
慧一居士3 小时前
web 系统对接飞书三方登录完整步骤实战使用示例
架构·系统架构