原生Pythonprint()
第一次构建图时将调用语句。看一下这个:
a = tf.placeholder(shape=None, dtype=tf.int32)
b = tf.placeholder(shape=None, dtype=tf.int32)
print("a is ",a," while b is ",b)
c = tf.add(a, b)
with tf.Session() as sess:
print(sess.run(c, feed_dict={a: 1, b: 2}))
print(sess.run(c, feed_dict={a: 3, b: 1}))
通过执行此代码块,输出为:
# a is Tensor("Placeholder:0", dtype=int32) while b is Tensor("Placeholder_1:0", dtype=int32)
# 3
# 4
另一方面,让我们看看tf.print()
:
a = tf.placeholder(shape=None, dtype=tf.int32)
b = tf.placeholder(shape=None, dtype=tf.int32)
print_op = tf.print("a is ",a," while b is ",b)
with tf.control_dependencies([print_op]):
c = tf.add(a, b)
with tf.Session() as sess:
print(sess.run(c, feed_dict={a: 1, b: 2}))
print(sess.run(c, feed_dict={a: 3, b: 1}))
因此,根据下面的输出,我们可以看到,如果我们添加依赖项tf.print
op 必须在任何时候运行c
运行后,我们可以看到我们想要的输出:
# a is 1 while b is 2
# 3
# a is 3 while b is 1
# 4
最后,tensor.eval()
与sess.run(tensor)
。然而,限制tensor.eval()
是你可以运行它来评估单个张量,而tf.Session
可用于评估多个张量sess.run([tensor1, tensor2])
。如果你问我,我总是会使用sess.run(list_of_tensors)
,评估我想要的尽可能多的张量,并打印出它们的值。