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

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

    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)
    

提交回复
热议问题