tf.Session():創建一個會話
tf.Session().as_default():創建一個默認會話
那麼問題來了,會話和默認會話有什麼區別呢?TensorFlow會自動生成一個默認的計算圖,如果沒有特殊指定,運算會自動加入這個計算圖中。TensorFlow中的會話也有類似的機制,但是TensorFlow不會自動生成默認的會話,而是需要手動指定。
tf.Session()創建一個會話,當上下文管理器退出時會話關閉和資源釋放自動完成。
tf.Session().as_default()創建一個默認會話,當上下文管理器退出時會話沒有關閉,還可以通過調用會話進行run()和eval()操作,代碼示例如下:
tf.Session()代碼示例:
import tensorflow as tf
a = tf.constant(1.0)
b = tf.constant(2.0)
with tf.Session() as sess:
print(a.eval())
print(b.eval(session=sess))
運行結果如下:
1.0
RuntimeError: Attempted to use a closed Session.
在打印張量b的值時報錯,報錯爲嘗試使用一個已經關閉的會話。
tf.Session().as_default()代碼示例:
import tensorflow as tf
a = tf.constant(1.0)
b = tf.constant(2.0)
with tf.Session().as_default() as sess:
print(a.eval())
print(b.eval(session=sess))
運行結果如下:
1.0
2.0
對於run()方法也是一樣,如果想讓默認會話在退出上下文管理器時關閉會話,可以調用sess.close()方法。
代碼示例如下:
import tensorflow as tf
a = tf.constant(1.0)
b = tf.constant(2.0)
with tf.Session().as_default() as sess:
print(a.eval())
sess.close()
print(b.eval(session=sess))
運行結果如下:
1.0
RuntimeError: Attempted to use a closed Session.
轉載:https://blog.csdn.net/Enchanted_ZhouH/article/details/77571939