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
相关推荐
MomentYY11 分钟前
AI 到底是“懂”,还是在“猜”?
前端·人工智能·ai编程
拾光拾趣录36 分钟前
为什么采用多路检索而不是单一向量检索?
人工智能
拾光拾趣录36 分钟前
Agent 编排器是怎么设计的?为什么这样设计?
人工智能
拾光拾趣录1 小时前
为什么选择 ReAct 模式而不是 Plan-and-Execute?
人工智能
沉默王二1 小时前
震惊!Claude Code这五个核心概念我居然才知道!
agent·ai编程·claude
身披彩云济沧海1 小时前
Trae 中配置 codegraph MCP
ai编程
武子康1 小时前
调查研究-196 CEO-Bench:Agent 不再只是“做任务“,而是要学会“经营一个系统“
人工智能
刘棕霆1 小时前
20—Token 计量与效率优化:每次测评消耗了多少 token
aigc·测试
用户329901675051 小时前
把AI返回的Markdown表格渲染成可排序表格
人工智能