首页 文章

如何在TensorFlow中打印Tensor对象的值?

提问于
浏览
184

我一直在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 的 Value ?

以下内容没有帮助:

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

我知道图表在 Sessions 上运行,但是如果没有在 session 中运行图表,我是否可以检查 Tensor 对象的输出?

13 回答

  • 17

    不,如果不运行图形,你就看不到张量的内容(做 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中解释的:

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

  • 1

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

    根据上面的答案,您可以使用特定的代码段打印产品,如下所示:

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

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

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

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

    如果您正在尝试编程模型,并且想要一种简单的方法来评估张量,tf.InteractiveSession允许您在程序开始时打开一个会话,然后将该会话用于所有 Tensor.eval() (和 Operation.run() )调用 . 这在交互式设置中可以更容易,例如shell或IPython笔记本,当在任何地方传递 Session 对象都很繁琐时 .

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


    [A]:要打印张量的值而不将其返回到Python程序,可以使用tf.Print()运算符,如Andrzej suggests in another answer . 请注意,您仍然需要运行图形的一部分来查看此op的输出,该输出将打印到标准输出 . 如果您正在运行分布式TensorFlow, tf.Print() 将其输出打印到运行该操作的任务的标准输出 . 这意味着如果您使用https://colab.research.google.com或任何其他Jupyter Notebook,那么您将无法在笔记本中看到tf.Print()的输出;在这种情况下,请参考this answer关于如何让它仍然打印 .

    [B]:您可能可以使用实验tf.contrib.util.constant_value()函数来获取常量张量的值,但是它并没有为许多运算符定义't intended for general use, and it isn't .

  • 4

    重申别人说的话,如果不运行图表就无法检查值 .

    任何寻找打印值的简单示例的人都可以使用一个简单的代码段如下 . 代码可以在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]]
    
  • 178

    我认为你需要得到一些正确的基础知识 . 通过上面的示例,您已经创建了张量(多维数组) . 但是要使张量流真正起作用,你必须启动“ session " and run your " operation " in the session. Notice the word " session " and " operation” . 你需要知道使用tensorflow的4件事:

    • 张量

    • 运营

    • 会话

    • 图表

    现在来自你写了什么,你给了张量,操作,但你没有会话运行,也没有图表 . 张量(图的边缘)流过图形并由操作(图形的节点)操纵 . 有默认图表,但您可以在会话中启动您的图表 .

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

    所以你可以看到你缺少的东西:

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

    希望能帮助到你!

  • 5

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

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

    基本上,在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:
        sess.run(c)
        c.eval()
    

    输出将是

    2018-08-01 14:41:00.397653:I tensorflow / core / common_runtime / gpu / gpu_device.cc:1471]添加可见的gpu设备:0 2018-08-01 14:41:00.397738:I tensorflow / core / common_runtime / GPU / gpu_device . cc:952]具有强度1边缘矩阵的设备互连StreamExecutor:2018-08-01 14:41:00.397759:I tensorflow / core / common_runtime / gpu / gpu_device.cc:958] 0 2018-08-01 14:41:00.397776 :I tensorflow / core / common_runtime / gpu / gpu_device.cc:971] 0:N 2018-08-01 14:41:00.398018:I tensorflow / core / common_runtime / gpu / gpu_device.cc:1084]创建TensorFlow设备(/ job:localhost / replica:0 / task:0 / device:GPU:0,2752 MB内存) - >物理GPU(设备:0,名称:GeForce GTX 1050 Ti,pci总线ID:0000:01:00.0,计算能力:6.1)数组([[1 . ,2.,3 . ],[4.,5.,6 . ]],dtype = float32)数组([[1 . ,2.,3 . ],[4 . ,5.,6 . ]],dtype = float32)

    我们得到两次打印的数组,因为会话只有张量常数通过而且我们有 c.eval()

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

    您应该将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]))
    
  • 128

    直到我执行完之后,即使在阅读完所有答案后,我也很难理解需要什么 . 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()
    
  • 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每晚构建以启用急切执行 . 可以找到预制的车轮here .

相关问题