我一直在使用TensorFlow中矩阵乘法的介绍性示例。
matrix1 = tf.constant([[3., 3.]])
matrix2 = tf.constant([[2.],[2.]])
product = tf.matmul(matrix1, matrix2)
当我打印乘积时,它显示为一个张量对象:
<tensorflow.python.framework.ops.Tensor object at 0x10470fcd0>
但是我怎么知道产品的价值呢?
下面的方法不起作用:
print product
Tensor("MatMul:0", shape=TensorShape([Dimension(1), Dimension(1)]), dtype=float32)
我知道图在会话上运行,但是没有任何方法可以检查张量对象的输出而不在会话中运行图吗?
特遣部队。Print现在已弃用,下面是如何使用tf。而是打印(小写p)。
虽然运行会话是一个很好的选择,但它并不总是正确的方法。例如,你可能想在一个特定的会话中打印一些张量。
新的print方法返回一个没有输出张量的打印操作:
print_op = tf.print(tensor_to_print)
由于它没有输出,所以不能像使用tf.Print那样将它插入图中。相反,您可以将它添加到会话中的控制依赖项中,以便打印它。
sess = tf.compat.v1.Session()
with sess.as_default():
tensor_to_print = tf.range(10)
print_op = tf.print(tensor_to_print)
with tf.control_dependencies([print_op]):
tripled_tensor = tensor_to_print * 3
sess.run(tripled_tensor)
有时,在较大的图(可能部分是在子函数中创建的)中,将print_op传播到会话调用是很麻烦的。然后,特遣部队。Tuple可用于将打印操作与另一个操作耦合,然后无论哪个会话执行该代码,该操作都将与该操作一起运行。以下是如何做到的:
print_op = tf.print(tensor_to_print)
some_tensor_list = tf.tuple([some_tensor], control_inputs=[print_op])
# Use some_tensor_list[0] instead of any_tensor below.