Skip to main content
 首页 » 编程设计

python之Tensorflow:与 Session() 相比,使用 InteractiveSession() 总是更方便吗

2025年02月15日29kuangbin

简单地使用 sub.eval() 而不是 sess.run(eval) 似乎更方便,所以总是更方便吗使用 InteractiveSession()?如果我们一直使用 InteractiveSession() 是否有任何折衷?

到目前为止,我看到的唯一“缺点”是我不能使用类似的东西:

with tf.InteractiveSession() as sess: 
   result = product.eval() #Where product is a simple matmul 
   print result 
   sess.close() 

相反,我必须立即定义 sess = tf.InteractiveSession。

请您参考如下方法:

从它们的实现来看,InteractiveSession 将自己设置为默认 session ,您后续的 eval() 调用可以使用此 session 。您应该能够在几乎所有使用 Session 的情况下使用 InteractiveSession。

一个小区别是您不需要在 with block 中使用 InteractiveSession:

sess = tf.InteractiveSession() 
# do your work 
sess.close() 

所以不要忘记在完成工作后关闭 session 。

这是 session.run() 和 eval() 之间的比较:In TensorFlow, what is the difference between Session.run() and Tensor.eval()?