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

相关推荐
人工智能AI技术3 小时前
10亿美元合作启发:AIGC正版IP应用开发,迪士尼+OpenAI技术拆解
人工智能
光羽隹衡3 小时前
深度学习——卷积神经网络实现手写数字识别
人工智能·深度学习·cnn
莫非王土也非王臣3 小时前
深度学习之对比学习
人工智能·深度学习·学习
AI_56783 小时前
Selenium+Python可通过 元素定位→操作模拟→断言验证 三步实现Web自动化测试
服务器·人工智能·python
冰西瓜6003 小时前
国科大高级人工智能期末复习(四)联结主义(下)——深度学习
人工智能·深度学习
蒜香拿铁3 小时前
【第三章】python算数运算符
python
檐下翻书1733 小时前
世界模型:AI理解物理空间的关键一步
人工智能
2013092416274 小时前
1968年 Hart, Nilsson, Raphael 《最小成本路径启发式确定的形式基础》A* 算法深度研究报告
人工智能·算法
InterestOriented4 小时前
破解银发学习痛点 兴趣岛 “普惠 + 品质” 模式打造积极老龄化范本
大数据·人工智能·学习
Mark_Aussie4 小时前
ADALog 日志异常检测
人工智能