class tf.Session
A class for running TensorFlow operations.
A Session
object encapsulates the environment in which Operation
objects are executed, and Tensor
objects are evaluated. For example:
# Build a graph.
a = tf.constant(5.0)
b = tf.constant(6.0)
c = a * b
# Launch the graph in a session.
sess = tf.Session()
# Evaluate the tensor `c`.
print(sess.run(c))
A session may own resources, such as variables, queues, and readers. It is important to release these resources when they are no longer required. To do this, either invoke the close()
method on the session, or use the session as a context manager. The following two examples are equivalent:
# Using the `close()` method.
sess = tf.Session()
sess.run(...)
sess.close()
# Using the context manager.
with tf.Session() as sess:
sess.run(...)
因此根据这个用法我去search到了如下python中的with-as statement(也称context manager),学习了一番,收获颇丰,参考到好的资料并理解为什么,在此分享。
reference:http://zhoutall.com/archives/325
先说明一个常见问题,文件打开:
1
2
3
4
5
6
7
|
try
:
f
=
open
(
'xxx'
)
do something
except
:
do something
finally
:
f.close()
|
其实我个人不止一次在网上看到有这么写的了,这个是错的。
首先正确的如下:
1
2
3
4
5
6
7
8
9
10
11
|
try
:
f
=
open
(
'xxx'
)
except
:
print
'fail to open'
exit(
-
1
)
try
:
|