我一直在使用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)

我知道图在会话上运行,但是没有任何方法可以检查张量对象的输出而不在会话中运行图吗?


当前回答

试试这个简单的代码!(不言自明)

import tensorflow as tf
sess = tf.InteractiveSession() # see the answers above :)
x = [[1.,2.,1.],[1.,1.,1.]]    # a 2D matrix as input to softmax
y = tf.nn.softmax(x)           # this is the softmax function
                               # you can have anything you like here
u = y.eval()
print(u)

其他回答

通过启用即时执行,你可以检查TensorObject的输出,而不用在会话中运行图。

只需添加以下两行代码: 导入tensorflow.contrib.eager为tfe tfe.enable_eager_execution ()

在你导入tensorflow之后。

在你的例子中打印产品的输出现在将是: 特遣部队。张量([[12。[],形状=(1,1),dtype=float32)

请注意,从现在(2017年11月)开始,你必须每晚安装一个Tensorflow构建来实现快速执行。预建车轮可以在这里找到。

试试这个简单的代码!(不言自明)

import tensorflow as tf
sess = tf.InteractiveSession() # see the answers above :)
x = [[1.,2.,1.],[1.,1.,1.]]    # a 2D matrix as input to softmax
y = tf.nn.softmax(x)           # this is the softmax function
                               # you can have anything you like here
u = y.eval()
print(u)

在Tensorflow V2中,使用:tf.keras.backend打印张量的值。print_tensor (x,消息= ")

基于上面的答案,使用特定的代码片段,您可以像这样打印产品:

import tensorflow as tf
#Initialize the session
sess = tf.InteractiveSession()

matrix1 = tf.constant([[3., 3.]])
matrix2 = tf.constant([[2.],[2.]])
product = tf.matmul(matrix1, matrix2)

#print the product
print(product.eval())

#close the session to release resources
sess.close()

特遣部队。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.