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

本文共 2167 字,大约阅读时间需要 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:

转载地址:http://ciojx.baihongyu.com/

你可能感兴趣的文章
《Java 2 图形设计卷Ⅱ- SWING》第12章 轻量容器
查看>>
macOS Sierra 代码显示未来 Mac 将搭载 ARM 芯片
查看>>
《Arduino家居安全系统构建实战》——1.3 部署安全系统的先决条件
查看>>
Linux 中如何通过命令行访问 Dropbox
查看>>
《jQuery移动开发》—— 1.3 小结
查看>>
使用 Flutter 反序列化 JSON 的一些选项
查看>>
开发进度——4
查看>>
使用原理视角看 Git
查看>>
Node.js 的module 系统
查看>>
经典c程序100 例
查看>>
页面中富文本的使用
查看>>
etymology-F
查看>>
FastD 最佳实践一: 构建 API
查看>>
Mycat安装以及使用测试
查看>>
JS里验证信息
查看>>
Microsoft Quantum Katas帮助开发人员探索使用Q#实现量子计算
查看>>
Akka actor tell, ask 函数的实现
查看>>
windows10 chrome 调试 ios safari 方法
查看>>
Hello , Ruby!
查看>>
Netty 4.1.35.Final 发布,经典开源 Java 网络服务框架
查看>>