TensorFlow Session会话控制&Variable变量详解
作者:诗蕊 时间:2023-06-21 12:37:42
这篇文章主要讲TensorFlow中的Session的用法以及Variable。
Session会话控制
Session是TensorFlow为了控制和输出文件的执行语句,运行session.run()就能获得运算结果或者部分运算结果。我们在这里使用一个简单的矩阵相乘的例子来解释Session的两个用法。
首先我们要加载TensorFlow并建立两个矩阵以及两个矩阵所做的运算。这里我们建立一个一行两列的matrix1和一个两行一列的matrix2,让它们做矩阵的乘法。tf.matmul相当于numpy中的dot方法,都是做矩阵的product。
import tensorflow as tf
matrix1 = tf.constant([[2, 2]])
matrix2 = tf.constant([[2], [2]])
product = tf.matmul(matrix1, matrix2)
接下来我们使用第一种会话控制Session来激活product并得到计算结果:
sess = tf.Session()
result = sess.run(product)
print(result)
sess.close()
运行结果为:[[8]]
还有另外一种Session的打开模式同样可以激活product:
with tf.Session() as sess:
result2 = sess.run(product)
print(result2)
运行结果同样是[[8]]。在这里我们不需要我们单独做sess.close()的操作。
variable变量
与python的变量不同,在TensorFlow中如果我们要定义一个变量,必须使用tf.Variable()来定义它才是个变量,括号中可以包含的参数有变量的值,变量的名称等。这里我们用一个简单的加法运算来解释变量的用法。
首先导入tensorflow并定义变量state, 常量one,以及运算方法tf.add, tf.assign
import tensorflow as tf
state = tf.Variable(0, name='counter')
# 输出变量名
print(state.name)
one = tf.constant(1)
new_value = tf.add(state, one)
# 将new_value加载到state里面,这时state的值就是new_value
update = tf.assign(state, new_value)
我们可以将变量打印出来得到变量的信息:
init = tf.global_variables_initializer()
接下来我们就要用Session来将变量激活进行运算,并打印出state的结果:
with tf.Session() as sess:
sess.run(init)
for _ in range(3):
sess.run(update)
print(sess.run(state))
这里我们让update运行3次,也就是做3次加法,运行结果为:
来源:https://blog.csdn.net/Katherine_hsr/article/details/79211688
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
详解Python3序列赋值、序列解包
python 如何去除字符串头尾的多余符号
python利用K-Means算法实现对数据的聚类案例详解
![](https://img.aspxhome.com/file/2023/3/134973_0s.png)
SQL Server数据库生成与执行SQL脚本详细教程
![](https://img.aspxhome.com/file/2023/3/98033_0s.jpg)
avalon js实现仿google plus图片多张拖动排序附源码下载
![](https://img.aspxhome.com/file/2023/8/132568_0s.gif)
一篇文章带你搞懂Python类的相关知识
![](https://img.aspxhome.com/file/2023/8/131008_0s.jpg)
基于Python实现口罩佩戴检测功能
![](https://img.aspxhome.com/file/2023/9/111989_0s.png)
Pycharm中import torch报错的快速解决方法
![](https://img.aspxhome.com/file/2023/0/101630_0s.jpg)
详解Mysql数据库平滑扩容解决高并发和大数据量问题
![](https://img.aspxhome.com/file/2023/1/107921_0s.png)
MySQL EXPLAIN执行计划解析
![](https://img.aspxhome.com/file/2023/1/121571_0s.png)
Linux安装Python3.8.1的教程详解
![](https://img.aspxhome.com/file/2023/3/123833_0s.jpg)
Django的分页器实例(paginator)
go语言实现聊天服务器的示例代码
在asp中使用存储过程
Python 模拟死锁的常见实例详解
![](https://img.aspxhome.com/file/2023/0/127730_0s.jpg)
Python fire模块(最简化命令行生成工具)的使用教程详解
![](https://img.aspxhome.com/file/2023/0/105280_0s.png)
Python算法思想集结深入理解动态规划
![](https://img.aspxhome.com/file/2023/8/112448_0s.png)
python案例练习合集
Python 打印不带括号的元组的实现
![](https://img.aspxhome.com/file/2023/0/99260_0s.png)