【问题标题】:Is necessary to use to both eval and run?是否需要同时使用 eval 和 run?
【发布时间】:2017-02-28 21:08:21
【问题描述】:

我从这个answer 了解了两者之间的区别。 但在大多数在线谈话/代码中,我发现人们使用以下两种方法:

import tensorflow as tf
a=tf.constant(5.0)
b=tf.constant(6.0)
c=a*b
with tf.Session() as sess:
    print(sess.run(c))
    print(c.eval())

我不明白这样做的必要性和实用性。

【问题讨论】:

    标签: python tensorflow


    【解决方案1】:

    在同一个会话中调用sess.run(c)c.eval(),提供完全相同的结果。

    您可以在代码中混合调用sess.run<tensor>.eval(),但这会使您的代码不太一致。

    在我看来,最好总是使用sess.run,因为在一次调用中您可以评估多个张量。

    相反,如果您使用<tensor>.eval(),您可以评估指定的<tensor>

    您可以看到运行此脚本的性能差异:

    import time
    import tensorflow as tf
    
    a=tf.constant(5.0)
    b=tf.constant(6.0)
    c=a*b
    
    start = time.time()
    with tf.Session() as sess:
        sess.run([c]*100)
    end_run = time.time() - start
    
    start = time.time()
    with tf.Session() as sess:
        for _ in range(100):
            c.eval()
    end_eval = time.time() - start
    
    print('Run: {}\nEval: {}'.format(end_run, end_eval))
    

    在 CPU (Intel i3) 上使用 Tensorflow r0.11 运行它会得到以下结果:

    Run: 0.009401798248291016
    Eval: 0.021142005920410156
    

    如您所见,执行包含 100 个元素的列表的 sess.run 调用要比执行 100 个 c.eval() 调用快得多。

    事实上,Tensorflow 只在 sess.run 调用中评估一次 c 张量,并在需要时重用结果进行其他计算。

    【讨论】:

      【解决方案2】:

      您的问题的快速回答是

      您只需要Session.run()Tensor.eval() 即可评估张量对象的值。人们通常使用Tensor.eval()来试验编程模型,即打印出张量的值来跟踪流程!例如,

      import tensorflow as tf
      
      a = tf.constant([1, 2], name='a')
      b = tf.constant([3, 4], name='b')
      c = tf.constant([1, 3], name='c')
      
      d = tf.add_n([a, b])
      e = tf.pow(d, c)
      
      printout_d = tf.Print(d, [a, b, d], 'Input for d and the result: ')
      printout_e = tf.Print(e, [d, c, e], 'Input for e and the result: ')
      
      with tf.Session() as sess:
          sess.run([d, e])
          printout_d.eval()
          printout_e.eval()
      

      在上面的代码中,您可以只需要sess.run([d, e]) 来执行图形。但是,在某些情况下,例如调试,您可以从printout_d.eval()printout_e.eval() 中受益。

      【讨论】:

        猜你喜欢
        • 2023-04-04
        • 2020-08-30
        • 1970-01-01
        • 1970-01-01
        • 2011-06-11
        • 1970-01-01
        • 2010-11-26
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多