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

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


当前回答

我不确定我是否遗漏了这里,但我认为最简单和最好的方法是使用tf.keras.backend。get_value API。

print(product)
>>tf.Tensor([[12.]], shape=(1, 1), dtype=float32)
print(tf.keras.backend.get_value(product))
>>[[12.]]

其他回答

import tensorflow as tf
sess = tf.InteractiveSession()
x = [[1.,2.,1.],[1.,1.,1.]]    
y = tf.nn.softmax(x)           

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

print(product.eval())
tf.reset_default_graph()
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核心程序由两个独立的部分组成:

构建计算图。 运行计算图。

因此,对于下面的代码,您只需构建计算图。

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

为了初始化TensorFlow程序中的所有变量,你必须显式调用一个特殊操作,如下所示:

init = tf.global_variables_initializer()

现在您构建了图并初始化了所有变量,下一步是计算节点,您必须在会话中运行计算图。会话封装了TensorFlow运行时的控件和状态。

下面的代码创建一个Session对象,然后调用它的run方法来运行足够的计算图来计算product:

sess = tf.Session()
// run variables initializer
sess.run(init)

print(sess.run([product]))

在Tensorflow 1.x中

import tensorflow as tf
tf.enable_eager_execution()
matrix1 = tf.constant([[3., 3.]])
matrix2 = tf.constant([[2.],[2.]])
product = tf.matmul(matrix1, matrix2)

#print the product
print(product)         # tf.Tensor([[12.]], shape=(1, 1), dtype=float32)
print(product.numpy()) # [[12.]]

用Tensorflow 2。X,默认开启急切模式。因此下面的代码与TF2.0一起工作。

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

#print the product
print(product)         # tf.Tensor([[12.]], shape=(1, 1), dtype=float32)
print(product.numpy()) # [[12.]]

我不确定我是否遗漏了这里,但我认为最简单和最好的方法是使用tf.keras.backend。get_value API。

print(product)
>>tf.Tensor([[12.]], shape=(1, 1), dtype=float32)
print(tf.keras.backend.get_value(product))
>>[[12.]]