zoukankan      html  css  js  c++  java
  • 【转载】 TensorFlow函数:tf.Session()和tf.Session().as_default()的区别

    原文地址:

    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

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

  • 相关阅读:
    04.sys
    leetcode算法-加油站
    Spring动态AOP
    (java反射-JDK动态代理)+CGLIB动态代理
    java反射-基础语法
    leetcode算法-验证回文串
    leetcode算法-盛最多水的容器
    leetcode算法-两数之和
    leetcode算法-三数之和
    leetcode算法-最长和谐子序列
  • 原文地址:https://www.cnblogs.com/devilmaycry812839668/p/12036362.html
Copyright © 2011-2022 走看看