问题:
tensorflow有两种方式:Session.run和 Tensor.eval,这两者的区别在哪?
答:
如果你有一个Tensor t,在使用t.eval()时,等价于:tf.get_default_session().run(t).
举例:
t = tf.constant(42.0)
sess = tf.Session()
with sess.as_default(): # or `with sess:` to close on exit
assert sess is tf.get_default_session()
assert t.eval() == sess.run(t)
这其中最主要的区别就在于你可以使用sess.run()在同一步获取多个tensor中的值,
例如:
t = tf.constant(42.0)
u = tf.constant(37.0)
tu = tf.mul(t, u)
ut = tf.mul(u, t)
with sess.as_default():
tu.eval() # runs one step
ut.eval() # runs one step
sess.run([tu, ut]) # evaluates both tensors in a single step
注意到:每次使用 eval 和 run时,都会执行整个计算图,为了获取计算的结果,将它分配给tf.Variable,然后获取。
如果有c = a + b
c.eval() 执行了a、b和c ,与c相关的变量都执行了。
看例子,如果想获取所有相关的tensor的值,应该如下:
import tensorflow as tf
with tf.Session() as sess:
box_confidence = tf.random_normal([1], mean=1, stddev=4, seed=1)
box_class_probs = tf.random_normal([4], mean=1, stddev=4, seed=1)
box_scores = tf.multiply(box_confidence, box_class_probs)
output = sess.run([box_confidence, box_class_probs, box_scores])
print(output)
一次性读取三个tensor。参考资料
下面这篇文章详细地介绍了Tensor与Flow:
罗斯基白话:TensorFlow+实战系列(一)之详解Tensor与Flow
第二篇文章也很有意义:
罗斯基白话:TensorFlow+实战系列(二)从零构建传统神经网络