How to print the value of a Tensor object in TensorFlow?

前端 未结 21 1900
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-11-22 07:44

I have been using the introductory example of matrix multiplication in TensorFlow.

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


        
21条回答
  •  滥情空心
    2020-11-22 08:02

    While other answers are correct that you cannot print the value until you evaluate the graph, they do not talk about one easy way of actually printing a value inside the graph, once you evaluate it.

    The easiest way to see a value of a tensor whenever the graph is evaluated (using run or eval) is to use the Print operation as in this example:

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

    Now, whenever we evaluate the whole graph, e.g. using b.eval(), we get:

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

提交回复
热议问题