【问题标题】:eval() and run() in tensorflow张量流中的 eval() 和 run()
【发布时间】:2016-12-23 13:41:24
【问题描述】:

我指的是 tensorflow 给出的Deep MNIST for Experts 教程。我在该教程的Train and Evaluate 部分有问题。他们在那里给出了一个示例代码,如下所示。

cross_entropy = tf.reduce_mean(-tf.reduce_sum(y_ * tf.log(y_conv),reduction_indices=[1]))
train_step = tf.train.AdamOptimizer(1e-4).minimize(cross_entropy)
correct_prediction = tf.equal(tf.argmax(y_conv,1), tf.argmax(y_,1))
accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))
sess.run(tf.initialize_all_variables())
for i in range(20000):
  batch = mnist.train.next_batch(50)
  if i%100 == 0:
    train_accuracy = accuracy.eval(feed_dict={x:batch[0], y_: batch[1], keep_prob: 1.0})
    print("step %d, training accuracy %g"%(i, train_accuracy))
  train_step.run(feed_dict={x: batch[0], y_: batch[1], keep_prob: 0.5})

print("test accuracy %g"%accuracy.eval(feed_dict={x: mnist.test.images,
                       y_: mnist.test.labels, keep_prob: 1.0}))

所以在这些代码段中,他们一次使用了accuracy.eval()。其他时间train_step.run()。据我所知,它们都是张量变量。

在某些情况下,我看到了类似的情况

sess.run(variable, feed_dict)

所以我的问题是这 3 种实现之间有什么区别。我怎么知道在什么时候使用什么......?

谢谢!!

【问题讨论】:

  • evalrun 都是重定向到 sess.run 的别名

标签: python python-2.7 tensorflow


【解决方案1】:

如果你只有一个默认会话,它们基本上是一样的。

来自https://github.com/tensorflow/tensorflow/blob/v1.12.0/tensorflow/python/framework/ops.py#L2351

op.run() 是调用 tf.get_default_session().run(op) 的快捷方式

来自https://github.com/tensorflow/tensorflow/blob/v1.12.0/tensorflow/python/framework/ops.py#L691

t.eval() 是调用 tf.get_default_session().run(t) 的快捷方式

张量和运算的区别:

张量:https://www.tensorflow.org/api_docs/python/tf/Tensor

操作:https://www.tensorflow.org/api_docs/python/tf/Operation

注意:Tensor 类将来会被 Output 取代。目前这两个是彼此的别名。

【讨论】:

    【解决方案2】:

    区别在于操作与张量。操作使用 run(),张量使用 eval()。

    TensorFlow FAQ 中似乎有对这个问题的引用: https://www.tensorflow.org/programmers_guide/faq#running_a_tensorflow_computation

    该部分解决了以下问题:Session.run() 和 Tensor.eval() 有什么区别?

    【讨论】:

      猜你喜欢
      • 2020-03-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-04-03
      • 1970-01-01
      • 2018-01-12
      • 2018-12-13
      • 1970-01-01
      相关资源
      最近更新 更多