tf.Session() vs tf.InteractiveSession()

Mainly taken from official documentation:

The only difference with a regular Session is that an InteractiveSession installs itself as the default session on construction. The methods Tensor.eval() and Operation.run() will use that session to run ops.

This allows to use interactive context, like shell, as it avoids having to pass an explicit Session object to run op:

sess = tf.InteractiveSession()
a = tf.constant(5.0)
b = tf.constant(6.0)
c = a * b
# We can just use 'c.eval()' without passing 'sess'
print(c.eval())
sess.close()

It is also possible to say, that InteractiveSession supports less typing, as allows to run variables without needing to constantly refer to the session object.

 

tf.InteractiveSession()加載它自身作爲默認構建的session,tensor.eval()和operation.run()取決於默認的session。

tf.InteractiveSession()輸入的代碼少,原因就是它允許變量不需要使用session就可以產生結構。

 

tf.InteractiveSession():它能讓你在運行圖的時候,插入一些計算圖,這些計算圖是由某些操作(operations)構成的。這對於工作在交互式環境中的人們來說非常便利,比如使用IPython。
tf.Session():需要在啓動session之前構建整個計算圖,然後啓動該計算圖。

意思就是在我們使用tf.InteractiveSession()來構建會話的時候,我們可以先構建一個session然後再定義操作(operation),如果我們使用tf.Session()來構建會話我們需要在會話構建之前定義好全部的操作(operation)然後再構建會話。

 

下面這三個是等價的:

sess = tf.InteractiveSession()

sess = tf.Session()
with sess.as_default():

with tf.Session() as sess:

示例:

import tensorflow as tf
import numpy as np

a=tf.constant([[1., 2., 3.],[4., 5., 6.]])
b=np.float32(np.random.randn(3,2))
c=tf.matmul(a,b)
init=tf.global_variables_initializer()
sess=tf.Session()
print (c.eval())

上面的代碼編譯是錯誤的,顯示錯誤如下:ValueError: Cannot evaluate tensor using `eval()`: No default session is registered. Use `with sess.as_default()` or pass an explicit session to `eval(session=sess)`

import tensorflow as tf
import numpy as np

a=tf.constant([[1., 2., 3.],[4., 5., 6.]])
b=np.float32(np.random.randn(3,2))
c=tf.matmul(a,b)
init=tf.global_variables_initializer()
sess=tf.InteractiveSession()
print (c.eval())

而用InteractiveSession()就不會出錯,說白了InteractiveSession()相當於:

sess=tf.Session()
with sess.as_default():

如果說想讓sess=tf.Session()起到作用,一種方法是上面的with sess.as_default();另外一種方法是

sess=tf.Session()
print (c.eval(session=sess))

其實還有一種方法也是with,如下:

import tensorflow as tf
import numpy as np

a=tf.constant([[1., 2., 3.],[4., 5., 6.]])
b=np.float32(np.random.randn(3,2))
c=tf.matmul(a,b)
init=tf.global_variables_initializer()
with tf.Session() as sess:
    #print (sess.run(c))
    print(c.eval())

------------------------------------------------------------------------------------------------------

參考:

https://blog.csdn.net/qq_14839543/article/details/77822916

https://www.cnblogs.com/cvtoEyes/p/9035047.html

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章