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

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


当前回答

基本上,在tensorflow中,当你创建任何类型的张量时,它们都会被创建并存储在里面,只有当你运行tensorflow会话时才能访问。假设你已经创建了一个常数张量 c = tf.constant ([(1.0, 2.0, 3.0), (4.0, 5.0, 6.0))) 不运行会话,您可以得到 —op:操作。计算这个张量的运算。 —value_index: int类型。生成这个张量的操作端点的索引。 —dtype: dtype类型。存储在这个张量中的元素类型。

为了得到这些值,你可以用你需要的张量运行一个会话:

with tf.Session() as sess:
    print(sess.run(c))
    sess.close()

输出将是这样的:

array([[1st, 2nd, 3rd], [4th, 5th, 6th]], 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.]]

重申其他人所说的,不运行图表是不可能检查值的。

下面是一个简单的代码片段,供寻找打印值的简单示例的人使用。代码可以在ipython notebook中执行,无需任何修改

import tensorflow as tf

#define a variable to hold normal random values 
normal_rv = tf.Variable( tf.truncated_normal([2,3],stddev = 0.1))

#initialize the variable
init_op = tf.initialize_all_variables()

#run the graph
with tf.Session() as sess:
    sess.run(init_op) #execute init_op
    #print the random values that we sample
    print (sess.run(normal_rv))

输出:

[[-0.16702934  0.07173464 -0.04512421]
 [-0.02265321  0.06509651 -0.01419079]]

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

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

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

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