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

前端 未结 21 1564
爱一瞬间的悲伤
爱一瞬间的悲伤 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:16

    In Tensorflow 2.0+ (or in Eager mode environment) you can call .numpy() method:

    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()) 
    
    0 讨论(0)
  • 2020-11-22 08:16

    You can use Keras, one-line answer will be to use eval method like so:

    import keras.backend as K
    print(K.eval(your_tensor))
    
    0 讨论(0)
  • 2020-11-22 08:16

    Using tips provided in https://www.tensorflow.org/api_docs/python/tf/print I use the log_d function to print formatted strings.

    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)
    
    0 讨论(0)
提交回复
热议问题