zoukankan      html  css  js  c++  java
  • tf.Session()、tf.InteractiveSession()

    tf.Session()和tf.InteractiveSession()的区别

    官方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();另外一种方法是

    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。

    我们都在通往真理的路上。
    萍水相逢逢萍水,浮萍之水水浮萍!
  • 相关阅读:
    Python进阶06 循环对象
    Python进阶05 循环设计
    Python进阶 函数的参数对应
    Python进阶01 词典
    Python基础 反过头来看看
    Python基础08 面向对象的基本概念
    利用zepto.js实现移动页面图片全屏滑动
    数组弃重方法
    fcc筆記
    文字颜色渐变效果
  • 原文地址:https://www.cnblogs.com/AIBigTruth/p/10288407.html
Copyright © 2011-2022 走看看