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

相关推荐
橙色小博1 分钟前
Python中openpyxl库的基础解析与代码实例
前端·python·excel·openpyxl
小叶爱吃鱼7 分钟前
web自动化-Selenium、Playwright、Robot Framework等自动化框架使用场景优劣对比
python·selenium·自动化
林林宋11 分钟前
DiTAR: Diffusion Transformer Autoregressive Modeling for Speech Generation
人工智能·深度学习·transformer
摘星编程27 分钟前
华为云Flexus+DeepSeek征文 | 基于Dify和DeepSeek-R1开发企业级AI Agent全流程指南
人工智能·华为云·deepseek·华为云flexus·dify-llm
lucky_lyovo30 分钟前
机器学习-线性回归基础
人工智能·机器学习·线性回归
元直数字电路验证1 小时前
[DS]使用 Python 库中自带的数据集来实现上述 50 个数据分析和数据可视化程序的示例代码
python·信息可视化·数据分析
一洽客服系统2 小时前
技术为器,服务为本:AI时代的客服价值重构
人工智能
moonsims4 小时前
无人机桥梁3D建模的拍摄频率
人工智能
LaughingZhu5 小时前
PH热榜 | 2025-05-29
前端·人工智能·经验分享·搜索引擎·产品运营
视觉语言导航6 小时前
俄罗斯无人机自主任务规划!UAV-CodeAgents:基于多智能体ReAct和视觉语言推理的可扩展无人机任务规划
人工智能·深度学习·无人机·具身智能