博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
What is a TensorFlow Session?
阅读量:6291 次
发布时间:2019-06-22

本文共 2218 字,大约阅读时间需要 7 分钟。

Sep 26, 2016

I’ve seen a lot of confusion over the rules of tf.Graph and tf.Session in TensorFlow. It’s simple:

  • A graph defines the computation. It doesn’t compute anything, it doesn’t hold any values, it just defines the operations that you specified in your code.
  • A session allows to execute graphs or part of graphs. It allocates resources (on one or more machines) for that and holds the actual values of intermediate results and variables.

Let’s look at an example.

Defining the Graph

We define a graph with a variable and three operations: variable always returns the current value of our variable. initialize assigns the initial value of 42 to that variable. assign assigns the new value of 13 to that variable.

graph = tf.Graph()with graph.as_default():    variable = tf.Variable(42, name='foo')    initialize = tf.initialize_all_variables()    assign = variable.assign(13)

On a side note: TensorFlow creates a default graph for you, so we don’t need the first two lines of the code above. The default graph is also what the sessions in the next section use when not manually specifying a graph.

Running Computations in a Session

To run any of the three defined operations, we need to create a session for that graph. The session will also allocate memory to store the current value of the variable.

with tf.Session(graph=graph) as sess:  sess.run(initialize)  sess.run(assign)  print(sess.run(variable))# Output: 13

As you can see, the value of our variable is only valid within one session. If we try to query the value afterwards in a second session, TensorFlow will raise an error because the variable is not initialized there.

with tf.Session(graph=graph) as sess:  print(sess.run(variable))# Error: Attempting to use uninitialized value foo

Of course, we can use the graph in more than one session, we just have to initialize the variables again. The values in the new session will be completely independent from the first one:

with tf.Session(graph=graph) as sess:  sess.run(initialize)  print(sess.run(variable))# Output: 42

Hopefully this short workthrough helped you to better understand tf.Session. Feel free to ask questions in the comments.

From:

转载于:https://www.cnblogs.com/wangduo/p/6995127.html

你可能感兴趣的文章
iOS--环信集成并修改头像和昵称(需要自己的服务器)
查看>>
PHP版微信权限验证配置,音频文件下载,FFmpeg转码,上传OSS和删除转存服务器本地文件...
查看>>
教程前言 - 回归宣言
查看>>
PHP 7.1是否支持操作符重载?
查看>>
Vue.js 中v-for和v-if一起使用,来判断select中的option为选中项
查看>>
Java中AES加密解密以及签名校验
查看>>
定义内部类 继承 AsyncTask 来实现异步网络请求
查看>>
VC中怎么读取.txt文件
查看>>
如何清理mac系统垃圾
查看>>
企业中最佳虚拟机软件应用程序—Parallels Deskto
查看>>
Nginx配置文件详细说明
查看>>
怎么用Navicat Premium图标编辑器创建表
查看>>
Spring配置文件(2)配置方式
查看>>
MariaDB/Mysql 批量插入 批量更新
查看>>
ItelliJ IDEA开发工具使用—创建一个web项目
查看>>
solr-4.10.4部署到tomcat6
查看>>
切片键(Shard Keys)
查看>>
淘宝API-类目
查看>>
virtualbox 笔记
查看>>
Git 常用命令
查看>>