總結
對簡單應用的情形(如單元測試),用以下格式可以得到更簡潔的代碼:
with tf.Session():
c.eval()
複制
如果你的代碼要處理多個graph和 session,更直白的方式可能是顯式調用Session.run():
sess = tf.Session()
sess.run(c)
複制
實驗代碼
>>> c = tf.constant(5.0)
>>> with tf.Session():
... c.eval()
...
2017-08-25 13:25:27.291743: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1030] Creating TensorFlow device (/gpu:0) -> (device: 0, name: GeForce GTX 1070, pci bus id: 0000:01:00.0)
5.0
>>> c = tf.constant(5.0)
>>> with tf.Session():
... c.eval()
...
2017-08-25 13:26:43.603831: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1030] Creating TensorFlow device (/gpu:0) -> (device: 0, name: GeForce GTX 1070, pci bus id: 0000:01:00.0)
5.0
>>>
# c.eval() 等同于 sess.run(c)
>>> c = tf.constant(5.0)
>>> sess = tf.Session()
2017-08-25 13:27:04.380039: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1030] Creating TensorFlow device (/gpu:0) -> (device: 0, name: GeForce GTX 1070, pci bus id: 0000:01:00.0)
>>> sess.run(c)
5.0
>>>
複制