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

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

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

我认为你需要掌握一些基本知识。通过上面的例子,你已经创建了张量(多维数组)。但是要让张量流真正工作,你必须启动一个“会话”,并在会话中运行你的“操作”。注意单词“session”和“operation”。 要使用张量流,你需要知道4件事:

张量 操作 会话 图

现在,从你写出来的东西中,你已经给出了张量和操作,但你没有运行会话,也没有图。张量(图的边)在图中流动,并由操作(图的节点)操作。有默认的图形,但你可以在会话中初始化你的。

当你说打印时,你只访问你定义的变量或常数的形状。

所以你可以看到你错过了什么:

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

希望能有所帮助!

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

下面是一个简单的代码片段,供寻找打印值的简单示例的人使用。代码可以在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]]

特遣部队。Print现在已弃用,下面是如何使用tf。而是打印(小写p)。

虽然运行会话是一个很好的选择,但它并不总是正确的方法。例如,你可能想在一个特定的会话中打印一些张量。

新的print方法返回一个没有输出张量的打印操作:

print_op = tf.print(tensor_to_print)

由于它没有输出,所以不能像使用tf.Print那样将它插入图中。相反,您可以将它添加到会话中的控制依赖项中,以便打印它。

sess = tf.compat.v1.Session()
with sess.as_default():
  tensor_to_print = tf.range(10)
  print_op = tf.print(tensor_to_print)
with tf.control_dependencies([print_op]):
  tripled_tensor = tensor_to_print * 3
sess.run(tripled_tensor)

有时,在较大的图(可能部分是在子函数中创建的)中,将print_op传播到会话调用是很麻烦的。然后,特遣部队。Tuple可用于将打印操作与另一个操作耦合,然后无论哪个会话执行该代码,该操作都将与该操作一起运行。以下是如何做到的:

print_op = tf.print(tensor_to_print)
some_tensor_list = tf.tuple([some_tensor], control_inputs=[print_op])
# Use some_tensor_list[0] instead of any_tensor below.