TensorFlow - the difference InteractiveSession and Session

Foreword

In practice, when tensorflow found a lot of very interesting fundamental questions, write a post about the record, both for the convenience of the review, and facilitate students' learning /

text

tf.Session () and tf.InteractiveSession () difference

The official tutorial is to say:

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.

What is the translation: tf.InteractiveSession () is an alternating conversation mode, which allow themselves to be the default session, that is to say in the context of a single user session, you do not need to specify which session with no need to change the session runs under the circumstances, can be up and running, this is the default benefits. In this case a run and eval () function may not indicate it session.

Compare:

import tensorflow as tf
import numpy as np

importtensorflow as tf
import numpy as np

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


The above code is compiled is wrong, display an error as follows:

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

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


And with InteractiveSession () can not go wrong, it simply InteractiveSession () is equivalent to:

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


In other words, if you want sess = tf.Session () functions, it is a method of the above

sess=tf.Session()
with sess as default:
    print (testc.eval())


Another method is

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


In fact, there is a way also with, as follows: 
Copy Code

import tensorflow as tf
import numpy as np

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


to sum up

tf.InteractiveSession () is the default own session (session) the user to operate, and tf.Session () is not the default, hence the need to specify the use of eval that session (session) when you start to calculate ()

Original: https: // blog .csdn.net / lvsehaiyang1993 / article / details /  80728675
 

Published 47 original articles · won praise 121 · views 680 000 +

Guess you like

Origin blog.csdn.net/guoyunfei123/article/details/93996564