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

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


当前回答

启用热切执行,这是在1.10版之后tensorflow中引入的。 它很容易使用。

# Initialize session
import tensorflow as tf
tf.enable_eager_execution()


# Some tensor we want to print the value of
a = tf.constant([1.0, 3.0])

print(a)

其他回答

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

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)

Tf.keras.backend.eval用于计算小表达式。

tf.keras.backend.eval(op)

TF - 1。x和TF 2.0兼容。


最小可验证示例

from tensorflow.keras.backend import eval

m1 = tf.constant([[3., 3.]])
m2 = tf.constant([[2.],[2.]])

eval(tf.matmul(m1, m2))
# array([[12.]], dtype=float32)

这很有用,因为您不必显式地创建Session或InteractiveSession。

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

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()

求一个Tensor对象的实际值最简单的方法是将它传递给session .run()方法,或者当你有一个默认会话(即在with tf.Session():块中,或见下文)时调用Tensor.eval()。一般来说[B],如果不在会话中运行一些代码,就不能打印张量的值。

如果你正在试验编程模型,想要一种简单的方法来求张量,tf。InteractiveSession允许你在程序开始时打开一个会话,然后将该会话用于所有的Tensor.eval()(和Operation.run())调用。这在交互设置中(比如shell或IPython笔记本)更容易,因为到处传递Session对象很乏味。例如,以下工作在Jupyter笔记本:

with tf.Session() as sess:  print(product.eval()) 

对于如此小的表达式来说,这可能看起来很愚蠢,但这是Tensorflow 1中的关键思想之一。x是延迟执行:构建一个大而复杂的表达式非常便宜,当你想计算它时,后端(你连接到一个会话)能够更有效地调度它的执行(例如并行执行独立的部分并使用gpu)。


[A]:要打印一个张量的值而不返回到你的Python程序,你可以使用tf.print()操作符,正如Andrzej在另一个答案中建议的那样。根据官方文件:

为了确保操作符运行,用户需要将生成的op传递给tf. compat_1 . session的run方法,或者通过指定tf. compat_1 .control_dependencies([print_op])将op作为已执行操作的控制依赖项,输出到标准输出。

还要注意:

在Jupyter笔记本和colabs中,tf。打印打印到笔记本单元格输出。它不会写入笔记本内核的控制台日志。

[B]:你可以使用tf.get_static_value()函数来获得给定张量的常数值,如果它的值是可以有效计算的。

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

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

在你导入tensorflow之后。

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

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