zl程序教程

您现在的位置是:首页 >  其它

当前栏目

【转载】 TensorFlow函数:tf.Session()和tf.Session().as_default()的区别

函数 区别 转载 session Tensorflow as Default TF
2023-09-11 14:19:20 时间

原文地址:

https://blog.csdn.net/Enchanted_ZhouH/article/details/77571939

 

 

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

 

 

 

       tf.Session():创建一个会话

       tf.Session().as_default():创建一个默认会话

       那么问题来了,会话和默认会话有什么区别呢?TensorFlow会自动生成一个默认的计算图如果没有特殊指定,运算会自动加入这个计算图中。TensorFlow中的会话也有类似的机制,但是TensorFlow不会自动生成默认的会话,而是需要手动指定

 

 

 


       tf.Session()创建一个会话,当上下文管理器退出时会话关闭和资源释放自动完成。

 

       tf.Session().as_default()创建一个默认会话,当上下文管理器退出时会话没有关闭,还可以通过调用会话进行run()和eval()操作,代码示例如下:

 

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.

 

 

 

 

 

 

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

 

————————————————
版权声明:本文为CSDN博主「Enchanted_ZhouH」的原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/Enchanted_ZhouH/article/details/77571939

 

 

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