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

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


当前回答

你可以打印出session中的张量值,如下所示:

import tensorflow as tf

a = tf.constant([1, 1.5, 2.5], dtype=tf.float32)
b = tf.constant([1, -2, 3], dtype=tf.float32)
c = a * b

with tf.Session() as sess:
    result = c.eval()
   
print(result)

其他回答

问题:如何在TensorFlow中打印一个张量对象的值?

答:

import tensorflow as tf

# Variable
x = tf.Variable([[1,2,3]])

# initialize
init = (tf.global_variables_initializer(), tf.local_variables_initializer())

# Create a session
sess = tf.Session()

# run the session
sess.run(init)

# print the value
sess.run(x)

我发现即使在阅读了所有的答案之后,我也不容易理解需要什么,直到我执行了这个。TensofFlow对我来说也是新的。

def printtest():
x = tf.constant([1.0, 3.0])
x = tf.Print(x,[x],message="Test")
init = (tf.global_variables_initializer(), tf.local_variables_initializer())
b = tf.add(x, x)
with tf.Session() as sess:
    sess.run(init)
    print(sess.run(b))
    sess.close()

但是您仍然可能需要执行会话返回的值。

def printtest():
    x = tf.constant([100.0])
    x = tf.Print(x,[x],message="Test")
    init = (tf.global_variables_initializer(), tf.local_variables_initializer())
    b = tf.add(x, x)
    with tf.Session() as sess:
        sess.run(init)
        c = sess.run(b)
        print(c)
        sess.close()

虽然其他答案是正确的,即在对图求值之前不能打印值,但它们并没有谈到一种简单的方法,即一旦对图求值,就可以在图中实际打印值。

当图被求值(使用run或eval)时,查看张量值的最简单方法是使用Print操作,如下例所示:

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

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

# Add print operation
a = tf.Print(a, [a], message="This is a: ")

# Add more elements of the graph using a
b = tf.add(a, a)

现在,当我们计算整个图时,例如使用b.c eval(),我们得到:

I tensorflow/core/kernels/logging_ops.cc:79] This is a: [1 3]

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

求一个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()函数来获得给定张量的常数值,如果它的值是可以有效计算的。