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

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

    tf.Print is now deprecated, here's how to use tf.print (lowercase p) instead.

    While running a session is a good option, it is not always the way to go. For instance, you may want to print some tensor in a particular session.

    The new print method returns a print operation which has no output tensors:

    print_op = tf.print(tensor_to_print)
    

    Since it has no outputs, you can't insert it in a graph the same way as you could with tf.Print. Instead, you can you can add it to control dependencies in your session in order to make it 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)
    

    Sometimes, in a larger graph, maybe created partly in subfunctions, it is cumbersome to propagate the print_op to the session call. Then, tf.tuple can be used to couple the print operation with another operation, which will then run with that operation whichever session executes the code. Here's how that is done:

    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.
    

提交回复
热议问题