TensorFlow入门:tf.InteractiveSession()与tf.Session()区别

tf.InteractiveSession():它能让你在运行图的时候,插入一些计算图,这些计算图是由某些操作(operations)构成的。这对于工作在交互式环境中的人们来说非常便利,比如使用IPython。

tf.Session():需要在启动session之前构建整个计算图,然后启动该计算图。

意思就是在我们使用tf.InteractiveSession()来构建会话的时候,我们可以先构建一个session然后再定义操作(operation),如果我们使用tf.Session()来构建会话我们需要在会话构建之前定义好全部的操作(operation)然后再构建会话。

官方tutorial是这么说的:

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.

翻译一下就是:tf.InteractiveSession()是一种交互式的session方式,它让自己成为了默认的session,也就是说用户在不需要指明用哪个session运行的情况下,就可以运行起来,这就是默认的好处。这样的话就是run()和eval()函数可以不指明session啦。

对比一下:

复制代码
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();另外一种方法是

扫描二维码关注公众号,回复: 1115196 查看本文章
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())
复制代码

总结:tf.InteractiveSession()默认自己就是用户要操作的session,而tf.Session()没有这个默认,因此用eval()启动计算时需要指明session。


猜你喜欢

转载自blog.csdn.net/m_z_g_y/article/details/80416226
今日推荐