【问题标题】:How to print the value of a Tensor object in TensorFlow?如何在 TensorFlow 中打印张量对象的值?
【发布时间】:2016-02-11 12:43:15
【问题描述】:

我一直在使用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 中运行图形?

【问题讨论】:

    标签: python tensorflow tensor


    【解决方案1】:

    评估Tensor 对象的实际值的最简单[A] 方法是将其传递给Session.run() 方法,或者在有默认会话时调用Tensor.eval() (即在with tf.Session(): 块中,或见下文)。通常[B],如果不在会话中运行一些代码,就无法打印张量的值。

    如果您正在试验编程模型,并且想要一种简单的方法来评估张量,tf.InteractiveSession 允许您在程序开始时打开一个会话,然后将该会话用于所有 Tensor.eval()(和 @ 987654331@) 电话。当在任何地方传递 Session 对象很乏味时,这在交互式环境中会更容易,例如 shell 或 IPython 笔记本。例如,以下内容适用于 Jupyter 笔记本:

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

    对于这么小的表达式,这可能看起来很傻,但是 Tensorflow 1.x 中的一个关键思想是延迟执行:构建一个大而复杂的表达式非常便宜,而且当你想要的时候为了评估它,后端(您通过 Session 连接到的)能够更有效地安排其执行(例如并行执行独立部分并使用 GPU)。


    [A]:要打印张量的值而不将其返回到 Python 程序,可以使用 tf.print() 运算符,如 Andrzej suggests in another answer。根据官方文档:

    为了确保操作符运行,用户需要将生成的操作传递给tf.compat.v1.Session的run方法,或者通过指定tf.compat.v1.control_dependencies([print_op]将操作作为执行操作的控制依赖),打印到标准输出。

    还要注意:

    在 Jupyter 笔记本和 colabs 中,tf.print 打印到笔记本单元格输出。它不会写入笔记本内核的控制台日志。

    [B]:您可能能够使用tf.get_static_value() 函数来获取给定张量的常量值,如果它的值是可有效计算的。

    【讨论】:

    • 可以在不调用 Session.run() 的情况下获取张量的某些属性。例如,您可以调用 tensor.get_shape()。在许多情况下,这为调试提供了足够的信息。
    • 另见 And 对下面 tf.Print 操作的回答。我在谷歌搜索“tensorflow print”时一直在找到这个stackoverflow答案,这个最佳答案听起来好像没有tf.Print op。
    • 我在答案中添加了一些警告,所以现在应该更清楚了。 (我不认为最初的提问者对获取张量的形状感兴趣,只是对值感兴趣。)
    • 有没有办法保存到文件而不是打印到控制台(通过 tf.Print)?
    • tf.Session() 在 Tensorflow 2 中不起作用。您可以改用 tf.compat.v1.Session()
    【解决方案2】:

    虽然其他答案是正确的,即您在评估图表之前无法打印该值,但他们并没有谈论一种在您评估图表后实际在图表中打印值的简单方法。

    在评估图形时(使用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]
    

    【讨论】:

    • 使用 a=tf.print 中的 a 到其他东西是非常重要的! tf.print(a,[a]) 否则不会做任何事情
    • 那么我们可以使用a.eval()
    • @FabioDias 我不明白你的意思吗?有时间请您详细说明...
    • 请注意tf.Print() 已被弃用并(现在)被删除。而是使用tf.print()。请参阅文档:tensorflow.org/api_docs/python/tf/Printtensorflow.org/api_docs/python/tf/print
    • 哇,我很惊讶一年后看到我自己的评论@yuqli,但现在我明白他的意思了。请参阅this 帖子,该帖子仍然是关于已弃用的 API,但想法可能相似。
    【解决方案3】:

    重申其他人所说的,不运行图表就无法检查值。

    对于任何寻找打印值的简单示例的人来说,一个简单的 sn-p 如下所示。代码在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]]
    

    【讨论】:

    • 仅供参考:WARNING:tensorflow:From &lt;ipython-input-25-8583e1c5b3d6&gt;:1: initialize_all_variables (from tensorflow.python.ops.variables) is deprecated and will be removed after 2017-03-02. Instructions for updating: Use 'tf.global_variables_initializer' instead.
    【解决方案4】:

    不,如果不运行图形,您将看不到张量的内容(执行session.run())。你能看到的只有:

    • 张量的维数(但我认为对于 TF 拥有的list of the operations 计算它并不难)
    • 将用于生成张量的操作类型(transpose_1:0random_uniform:0
    • 张量中的元素类型 (float32)

    我没有在文档中找到这个,但我相信变量的值(以及一些常量在赋值时没有计算出来)。


    看看这个例子:

    import tensorflow as tf
    from datetime import datetime
    dim = 7000
    

    第一个示例,我只是启动一个随机数的常量张量,几乎在同一时间运行,与暗淡无关 (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 中有解释:

    张量对象是操作结果的符号句柄, 但实际上并不保存操作输出的值。

    【讨论】:

      【解决方案5】:

      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 中,Eager 模式默认启用。因此以下代码适用于 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.]]
      

      【讨论】:

      • 我已经安装了 TensorFlow 版本 1.13.2 并启用了急切执行(检查是否使用 tf.executing_eagerly() 运行)并在尝试评估时收到错误 'Tensor' object has no attribute 'numpy'自定义损失函数中的张量值。我非常感谢任何帮助解决这个问题。
      • @NikoGamulin 确保已将 tf.compat.v1.enable_eager_execution() 放在脚本的开头。我有版本 1.14.0,我在 PyCharm 上运行我的脚本,并且 tensor.numpy() 工作
      • @NikoGamulin 只有当您尝试在图形模式下访问张量时才会出现该错误。我认为,可能是急切执行没有正确启用。为了检查急切执行,只需定义 a=tf.constant(2.0), b=tf.constant(3.0), print(tf.add(a,b))。如果您看到答案为 5.0,则正确启用了 Eager。
      【解决方案6】:

      我认为您需要正确掌握一些基础知识。通过上面的示例,您已经创建了张量(多维数组)。但要让张量流真正发挥作用,您必须启动“会话”并在会话中运行“操作”。注意单词“会话”和“操作”。 使用 TensorFlow 需要了解 4 件事:

      1. 张量
      2. 运营
      3. 会话
      4. 图表

      现在,根据您写的内容,您已经给出了张量和操作,但您没有运行会话,也没有图表。张量(图的边缘)流经图并由操作(图的节点)操纵。有默认图表,但您可以在会话中启动您的图表。

      当您说 print 时,您只能访问您定义的变量或常量的形状。

      所以你可以看到你缺少什么:

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

      希望对你有帮助!

      【讨论】:

        【解决方案7】:

        tf.keras.backend.eval 对于评估小表达式很有用。

        tf.keras.backend.eval(op)
        

        兼容 TF 1.x 和 TF 2.0。


        可验证的最小示例

        from tensorflow.keras.backend import eval
        
        m1 = tf.constant([[3., 3.]])
        m2 = tf.constant([[2.],[2.]])
        
        eval(tf.matmul(m1, m2))
        # array([[12.]], dtype=float32)
        

        这很有用,因为您不必显式创建SessionInteractiveSession

        【讨论】:

        • 这里可能发生什么? AttributeError: 'Tensor' object has no attribute '_numpy'
        【解决方案8】:

        根据上面的答案,使用您的特定代码 sn-p 您可以像这样打印产品:

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

        【讨论】:

          【解决方案9】:

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

          【讨论】:

          • tf.print(product) 也给了我与 TF 2.0 的print(product.numpy()) 相同的输出。
          【解决方案10】:

          通过启用eager execution,您无需在会话中运行图形即可检查 TensorObject 的输出。

          只需添加以下两行代码: import tensorflow.contrib.eager as tfe tfe.enable_eager_execution()

          就在你之后import tensorflow

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

          请注意,从现在(2017 年 11 月)开始,您必须安装 Tensorflow 每晚构建版本才能启用 Eager Execution。预制轮子可以在here找到。

          【讨论】:

            【解决方案11】:

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

            【讨论】:

              【解决方案12】:

              您应该将 TensorFlow Core 程序视为由两个独立的部分组成:

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

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

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

              【讨论】:

                【解决方案13】:

                您可以使用 Keras,一条答案就是使用 eval 方法,如下所示:

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

                【讨论】:

                  【解决方案14】:

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

                  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)
                  

                  【讨论】:

                    【解决方案15】:

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

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

                    【讨论】:

                      【解决方案16】:

                      即使在阅读了所有答案之后,直到我执行此操作,我仍然无法轻松理解所需的内容。 TensofFlow 对我来说也是新的。

                      def printtest():
                      x = tf.constant([1.0, 3.0])
                      x = tf.Print(x,[x],message="Test")
                      init = (tf.global_variables_initializer(), tf.local_variables_initializer())
                      b = tf.add(x, x)
                      with tf.Session() as sess:
                          sess.run(init)
                          print(sess.run(b))
                          sess.close()
                      

                      但您仍然可能需要执行会话返回的值。

                      def printtest():
                          x = tf.constant([100.0])
                          x = tf.Print(x,[x],message="Test")
                          init = (tf.global_variables_initializer(), tf.local_variables_initializer())
                          b = tf.add(x, x)
                          with tf.Session() as sess:
                              sess.run(init)
                              c = sess.run(b)
                              print(c)
                              sess.close()
                      

                      【讨论】:

                        【解决方案17】:

                        在 TensorFlow V2 中,使用:tf.keras.backend.print_tensor(x, message='') 打印张量值

                        【讨论】:

                          【解决方案18】:

                          你可以打印出会话中的张量值如下:

                          import tensorflow as tf
                          
                          a = tf.constant([1, 1.5, 2.5], dtype=tf.float32)
                          b = tf.constant([1, -2, 3], dtype=tf.float32)
                          c = a * b
                          
                          with tf.Session() as sess:
                              result = c.eval()
                             
                          print(result)
                          

                          【讨论】:

                            【解决方案19】:

                            基本上,在 tensorflow 中,当您创建任何类型的张量时,它们会被创建并存储在其中,只有在您运行 tensorflow 会话时才能访问。假设您创建了一个常量张量
                            c = tf.constant([[1.0, 2.0, 3.0], [4.0, 5.0, 6.0]])
                            无需运行会话,您可以获得
                            - op:一个操作。计算此张量的操作。
                            - value_index:一个整数。产生此张量的操作端点的索引。
                            - dtype:一个 DType。存储在此张量中的元素类型。

                            要获取值,您可以使用所需的张量运行会话:

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

                            输出将是这样的:

                            数组([[1., 2., 3.], [4., 5., 6.]], dtype=float32)

                            【讨论】:

                              【解决方案20】:

                              启用 tensorflow 1.10 之后引入的急切执行。 它非常易于使用。

                              # Initialize session
                              import tensorflow as tf
                              tf.enable_eager_execution()
                              
                              
                              # Some tensor we want to print the value of
                              a = tf.constant([1.0, 3.0])
                              
                              print(a)
                              

                              【讨论】:

                                【解决方案21】:

                                使用https://www.tensorflow.org/api_docs/python/tf/print 中提供的技巧我使用log_d 函数来打印格式化字符串。

                                import tensorflow as tf
                                
                                def log_d(fmt, *args):
                                    op = tf.py_func(func=lambda fmt_, *args_: print(fmt%(*args_,)),
                                                    inp=[fmt]+[*args], Tout=[])
                                    return tf.control_dependencies([op])
                                
                                
                                # actual code starts now...
                                
                                matrix1 = tf.constant([[3., 3.]])
                                matrix2 = tf.constant([[2.],[2.]])
                                product = tf.matmul(matrix1, matrix2)
                                
                                with log_d('MAT1: %s, MAT2: %s', matrix1, matrix2): # this will print the log line
                                    product = tf.matmul(matrix1, matrix2)
                                
                                with tf.Session() as sess:
                                    sess.run(product)
                                

                                【讨论】:

                                  【解决方案22】:
                                  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()
                                  

                                  【讨论】:

                                    【解决方案23】:

                                    tf.Print 现已弃用,以下是如何使用 tf.print(小写 p)代替。

                                    虽然运行会话是一个不错的选择,但它并不总是可行的方法。例如,您可能希望在特定会话中打印一些张量。

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

                                    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 传播到会话调用很麻烦。然后,tf.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.
                                    

                                    【讨论】:

                                      【解决方案24】:

                                      问题:如何在TensorFlow中打印一个Tensor对象的值?

                                      答案:

                                      import tensorflow as tf
                                      
                                      # Variable
                                      x = tf.Variable([[1,2,3]])
                                      
                                      # initialize
                                      init = (tf.global_variables_initializer(), tf.local_variables_initializer())
                                      
                                      # Create a session
                                      sess = tf.Session()
                                      
                                      # run the session
                                      sess.run(init)
                                      
                                      # print the value
                                      sess.run(x)
                                      

                                      【讨论】:

                                        猜你喜欢
                                        • 2017-11-10
                                        • 2016-09-01
                                        • 2023-04-02
                                        • 1970-01-01
                                        • 1970-01-01
                                        • 2021-12-16
                                        • 2023-01-11
                                        • 2017-09-12
                                        相关资源
                                        最近更新 更多