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
相关推荐
耿雨飞3 小时前
第三章:LangChain Classic vs. 新版 LangChain —— 架构演进与迁移指南
人工智能·架构·langchain
BizViewStudio3 小时前
甄选 2026:AI 重构新媒体代运营行业的三大核心变革与落地路径
大数据·人工智能·新媒体运营·媒体
俊哥V3 小时前
AI一周事件 · 2026年4月8日至4月14日
人工智能·ai
墨风如雪3 小时前
VPS 买回来第一天该干什么?我的开机必做清单
aigc
GitCode官方3 小时前
G-Star Gathering Day 杭州站回顾
人工智能·开源·atomgit
宇擎智脑科技4 小时前
开源 AI Agent 架构设计对比:Python 单体 vs TypeScript 插件化
人工智能·openclaw·hermes agent
冷色系里的一抹暖调5 小时前
OpenClaw Docker部署避坑指南:服务启动成功但网页打不开?
人工智能·docker·容器·openclaw
曹牧5 小时前
自动编程AI落地方案‌
人工智能
天云数据5 小时前
Harness革命:企业级AI从“失控野马”到“价值引擎”的跃迁
人工智能
汽车仪器仪表相关领域5 小时前
NHVOC-70系列固定污染源挥发性有机物监测系统:精准破局工业VOCs监测痛点,赋能环保合规升级
大数据·人工智能·安全性测试