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

相关推荐
chenchihwen31 分钟前
AI代码开发宝库系列:FAISS向量数据库
数据库·人工智能·python·faiss·1024程序员节
张登杰踩1 小时前
工业产品表面缺陷检测方法综述:从传统视觉到深度学习
人工智能·深度学习
sponge'1 小时前
opencv学习笔记6:SVM分类器
人工智能·机器学习·支持向量机·1024程序员节
zandy10111 小时前
2025年AI IDE的深度评测与推荐:从单一功能效率转向生态壁垒
ide·人工智能
andyguo2 小时前
ChatGPT Atlas vs Chrome:AI 浏览器的新纪元
人工智能·chrome·chatgpt
AI视觉网奇2 小时前
json 可视化 2025 coco json
python·1024程序员节
北京迅为2 小时前
【北京迅为】iTOP-4412精英版使用手册-第六十七章 USB鼠标驱动详解
linux·人工智能·嵌入式·4412
mit6.8242 小时前
[nanoGPT] ChatGPT 的 LLM 的全栈实现 | 快速上手
python
DKunYu2 小时前
2.1线性回归
pytorch·python·深度学习·1024程序员节
大飞记Python2 小时前
实战分享:一键自动化下载指定版本的Chrome及Chromedriver(附Python源码)
chrome·python·自动化