TensorFlow之Session

目录

前言

会话(Session)是用来执行图中的运算的上下文。所有的运算必须在一个会话中执行。在 TensorFlow 2.x 中,会话的概念已经被简化,默认情况下,所有的操作都会立即执行。

Tensorflow1.x

静态图(无eager mode)

学习额外概念

如图、会话、变量、占位符等

python 复制代码
# Tensorflow1.0实现
import tensorflow as tf

# 构建计算图
x = tf.Variable(0.)
y = tf.Variable(1.)
add_op = x.assign(x + y)  # x = x + y
div_op = y.assign(y / 2)  # y = y / 2

# TensorFlow1.0中必须先打开会话,才能计算数据流图
with tf.Session() as sess:
	sess.run(tf.global_variables_initializer())  # 初始化会话
	for iteration in range(50):
		sess.run(add_op)
		sess.run(div_op)
	print(x.eval())  # 也可用sess.eval(x)

如果你的TensorFlow版本是2.x,则会提示报错:AttributeError: module 'tensorflow' has no attribute 'Session'

Tensorflow2.x

动态图(eager mode默认打开)

Eager mode避免1.0缺点,直接集成在Python中

python 复制代码
import tensorflow as tf

x = tf.constant(0.)
y = tf.constant(1.)
for iteration in range(50):
	x = x + y
	y = y / 2
print(x.numpy())

结果:

2.0

相关推荐
曲幽几秒前
FastAPI + Celery 实战:异步任务的坑与解法,我帮你踩了一遍
redis·python·fastapi·web·async·celery·background·task·queue
亦复何言??7 分钟前
BeyondMimic 论文解析
人工智能·算法·机器人
深蓝海拓8 分钟前
使用@property将类方法包装为属性
开发语言·python
Lee川9 分钟前
🛠️ LangChain Tools 实战指南:让 AI 拥有“动手能力”
人工智能
gorgeous(๑>؂<๑)11 分钟前
【CVPR26-索尼】EW-DETR:通过增量低秩检测Transformer实现动态世界目标检测
人工智能·深度学习·目标检测·计算机视觉·transformer
xianluohuanxiang14 分钟前
新能源功率预测的“生死局”:从“能报曲线”到“能做收益”,中间差的不是一点算法
人工智能
码农垦荒笔记32 分钟前
Claude Code 2026 年 3 月全面进化:Auto 模式、Computer Use 与云端持续执行重塑 AI 编程工作流
人工智能·ai 编程·claude code·agentic coding·computer use
threerocks37 分钟前
【Claude Code 系列课程】01 | Claude Code 架构全览
人工智能·ai编程·claude
熊猫代跑得快39 分钟前
Agent 通用架构入门学习
人工智能·agent·智能体
格林威40 分钟前
Baumer相机锂电池极片裁切毛刺检测:防止内部短路的 5 个核心方法,附 OpenCV+Halcon 实战代码!
开发语言·人工智能·数码相机·opencv·计算机视觉·c#·视觉检测