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

相关推荐
前端粉刷匠2 分钟前
2025 年是 Agent 的,2026 年是 Harness 的——AI 编程 Harness 架构深度解析
前端·人工智能
小白马突突突3 分钟前
零信脱敏现已支持导出适合AI 分析的 脱敏 Markdown
人工智能
weixin_BYSJ19877 分钟前
flask民族服饰饰品商城小程序---附源码37399
java·javascript·spring boot·python·小程序·django·php
skywalk81638 分钟前
硬核移植实录:在 FreeBSD 15.1 上从零跑起 DeepSeek 智能体 harness(附完整踩坑手册)
人工智能·freebsd·deepseek·harness
武子康14 分钟前
GPT-Live 分析研究:从回合式语音到连续交互循环
人工智能·llm·agent
fail_to_code15 分钟前
从 Lighthouse 83 到 100:一次 Vue 项目的性能排查实录
前端·人工智能
用户693717500138421 分钟前
DeepSeek 调价正式生效:一夜涨 11 倍,靠低价薅羊毛的日子结束了
前端·人工智能·后端
帅气的小峰24 分钟前
pybind11与nanobind可以共存吗?如何迁移?
c++·python·cuda·推理引擎
JAI科研25 分钟前
Deepseek Agent Harness教程(二) | DeepSeek Harness 设计思路
人工智能·深度学习·算法·机器学习·自然语言处理·transformer·vllm
探物 AI26 分钟前
yolo目标检测中的激活函数对比
人工智能·yolo·目标检测