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

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


当前回答

你可以使用Keras,一行回答将使用eval方法,如下所示:

import keras.backend as K
print(K.eval(your_tensor))

其他回答

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

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

请注意,tf.Print()将改变张量名称。 如果你想要打印的张量是一个占位符,那么向它输入数据将会失败,因为在输入过程中找不到原始的名称。 例如:

import tensorflow as tf
tens = tf.placeholder(tf.float32,[None,2],name="placeholder")
print(eval("tens"))
tens = tf.Print(tens,[tens, tf.shape(tens)],summarize=10,message="tens:")
print(eval("tens"))
res = tens + tens
sess = tf.Session()
sess.run(tf.global_variables_initializer())

print(sess.run(res))

输出是:

python test.py
Tensor("placeholder:0", shape=(?, 2), dtype=float32)
Tensor("Print:0", shape=(?, 2), dtype=float32)
Traceback (most recent call last):
[...]
InvalidArgumentError (see above for traceback): You must feed a value for placeholder tensor 'placeholder' with dtype float

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

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

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 2.0+(或Eager模式环境)中,你可以调用.numpy()方法:

import tensorflow as tf

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

print(product.numpy())