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

相关推荐
大刚测试开发实战10 小时前
TestHub V0.2.2版本发布,附更新指南
人工智能
冬奇Lab11 小时前
Agent 系列(21):Harness 测试工程——45 个测试怎么设计,以及它发现了什么 bug
人工智能·llm·agent
冬奇Lab11 小时前
每日一个开源项目(第133篇):EchoBird - 把 AI 工具的安装和部署做成傻瓜操作
人工智能·开源·资讯
程序员龙叔11 小时前
编写高质量 Skill 系列 -- 如何设计需求分析与用例生成的 SKILL
自动化测试·软件测试·python·软件测试工程师·接口测试·性能测试·skill·ai测试
IT_陈寒12 小时前
Redis的SETNX并发问题让我加了三天班
前端·人工智能·后端
用户51914958484514 小时前
Windows 渗透测试载荷加载器 POC 工具集
人工智能·aigc
大树8814 小时前
金刚石散热越强,管路越先见顶
大数据·运维·服务器·人工智能·ai
用户83562907805114 小时前
使用 Python 操作 Word 内容控件
后端·python
通信小呆呆14 小时前
当算法有了“五感”:多模态数据融合如何向人体感官协同学习?
人工智能·学习·算法·机器学习·机器人
施小赞14 小时前
普通 RAG vs GraphRAG 核心对比
人工智能·ai