2015-11-10 91 views
131

我一直在使用TensorFlow中矩阵乘法的例子。如何在TensorFlow中打印张量对象的值?

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

当我打印的产品,它会显示它作为一个Tensor对象:

<tensorflow.python.framework.ops.Tensor object at 0x10470fcd0> 

但是我怎么知道的product价值?

以下没有帮助:

print product 
Tensor("MatMul:0", shape=TensorShape([Dimension(1), Dimension(1)]), dtype=float32) 

我知道,图表上Sessions运行,但是是不是有什么办法可以检查Tensor对象的输出,而不运行在session图?

回答

134

,最简单的方式*来评估Tensor对象的实际值是将它传递给Session.run()方法,或拨打Tensor.eval()当你有一个默认会话(即,在一个with tf.Session():块,或见下文)。一般来说,**你不能在会话中运行一些代码的情况下打印张量的值。

如果您正在使用的编程模型试验,并希望有一个简单的方法来评价张量,该tf.InteractiveSession可以让你在你的程序开始打开会话,然后用所有Tensor.eval()(和Operation.run())这届会议呼叫。在一个交互式设置中,例如shell或IPython笔记本,当在任何地方传递一个对象时都很麻烦。

这似乎是愚蠢的,这样一个小的表达,但在Tensorflow的主要观点之一是延迟执行:这是非常廉价的构建一个庞大而复杂的表情,当你要评估它的背结尾(与Session连接时)可以更高效地安排其执行(例如,并行执行独立部分并使用GPU)。


*  要打印张量的值,而无需将其返回到你的Python程序,你可以使用tf.Print()运算符,如Andrzej suggests in another answer。请注意,您仍需要运行部分图表来查看此op的输出,该输出将打印到标准输出。如果您正在运行分布式TensorFlow,则tf.Print()将将其输出打印到运行该任务的任务的标准输出。

**  您可能能够使用实验tf.contrib.util.constant_value()函数来获得恒定的张量的值,但它不适用于一般用途,并且不为许多运营商定义的。

+8

可以在不调用Session.run()的情况下得到张量的某些属性。例如,您可以调用tensor.get_shape()。在很多情况下,这给调试提供了足够的信息。 –

+3

另请参见以下关于tf.Print的答案。我一直在寻找这个stackoverflow的答案,同时搜索“tensorflow打印”,这个最重要的答案听起来像没有tf.Print操作。 –

+1

我在回答中增加了一些注意事项,所以现在应该更清楚了。 (我不认为最初的提问者有兴趣获得张量的形状,只是价值。) – mrry

15

不,您不能在没有运行图形的情况下(做session.run())看到张量的内容。你可以看到的唯一的事情是:

  • 张量的维度(但我相信它是不是很难计算它为TF具有list of the operations
  • 类型将用于生成操作的张量(transpose_1:0random_uniform:0)在张量
  • 类型的元素(float32

我没有在文档中发现这一点,但我相信变量的值(和一些常量在分配时不计算)。


看看这个例子:

import tensorflow as tf 
from datetime import datetime 
dim = 7000 

第一个例子,我刚开始的随机数不变张量运行大约在同一时间irrespectibly的暗淡(0:00:00.003261

startTime = datetime.now() 
m1 = tf.truncated_normal([dim, dim], mean=0.0, stddev=0.02, dtype=tf.float32, seed=1) 
print datetime.now() - startTime 

在第二种情况下,实际获取常数并分配值时,时间显然取决于暗(0:00:01.244642

startTime = datetime.now() 
m1 = tf.truncated_normal([dim, dim], mean=0.0, stddev=0.02, dtype=tf.float32, seed=1) 
sess = tf.Session() 
sess.run(m1) 
print datetime.now() - startTime 

而且你可以通过计算的东西(d = tf.matrix_determinant(m1),记住,时间将在O(dim^2.8)运行)

附:它更清晰我发现了它在documentation解释说:

张量对象是一个象征性的手柄操作, 的结果,但实际上并没有存储操作的输出值。

101

虽然其他答案是正确的,直到您评估图表时才能打印该值,但他们不会谈论在图表中实际打印值的简单方法,只要您对其进行评估即可。

(使用runeval)看每当图形被评估的张量的值的最简单方法是使用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.eval(),我们得到:

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

它是非常重要的,你使用从a = tf.print到另一个! tf.print(a,[a])不会做任何其他的事情 –

+1

然后我们可以使用'a.eval()'! –

17

重申别人说什么,它不是可以检查值,而不运行图。

对于任何想要打印值的简单示例的人来说,简单的代码片段如下所示。该代码可以不加任何修改在IPython的笔记本电脑中执行

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]] 
+2

仅供参考:'警告:tensorflow:从:1:initialize_all_variables(来自tensorflow.python.ops.variables)已弃用,2017-03-02之后将被删除。 更新说明: 改为使用'tf.global_variables_initializer'。 –

6

基于以上问题的答案,与您的特定代码片断,可以打印产品是这样的:

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

试试这个简单的代码! (这是自我解释)

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

我认为你需要得到一些基本面的权利。通过上面的示例,您创建了张量(多维数组)。但是为了使张量流动真正起作用,您必须在会话中启动“会话”并运行您的“操作”。注意单词“会话”和“操作”。 你需要知道的4件事与tensorflow工作:

  1. 张量
  2. 操作
  3. 会议
  4. 图形

现在从你写出来,你已经给了张量,和该操作,但你没有会议运行,也没有图形。张量(图的边)流过图并由操作(图的节点)操纵。有默认图表,但您可以在会话中启动您的图表。

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

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

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

希望它能帮助!

2

请注意,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 
4

你应该想到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])) 
2

可以检查TensorObject的输出,通过启用eager execution。之后你import tensorflow import tensorflow.contrib.eager as tfe tfe.enable_eager_execution()

只需添加以下代码两行。

print product在你的例子现在输出将是: tf.Tensor([[ 12.]], shape=(1, 1), dtype=float32)

需要注意的是,截至目前(2017年11月),你必须安装一个Tensorflow夜间生成,使急于执行。预制轮可以在here找到。