5

I am trying to understand some code from a reinforcement learning algorithm. In order to do that I am trying to print the value of a tensor.

I made a simple piece of code to show what I mean.

import tensorflow as tf
from keras import backend as K

x = K.abs(-2.0)
tf.Print(x,[x], 'x')

The goal is to have the value '2' printed(the absolute value of -2). But I only get back the following:

Using TensorFlow backend.

Process finished with exit code 0

Nothing, how can I print the value '2' just like a print('...') statement would do?

nbro
  • 15,395
  • 32
  • 113
  • 196
JorDik
  • 127
  • 2
  • 2
  • 7

3 Answers3

5

If you are using Jupyter Notebook, then tf.Print() so far isn't compatible and would be printing the output to Notebook's server output as is described in the docs

In the tensorflow documentation, here is how Tensors are described:

When writing a TensorFlow program, the main object you manipulate and pass around is the tf.Tensor. A tf.Tensor object represents a partially defined computation that will eventually produce a value.

Hence, you would have to initialize them with a tf.Session() to get their value. To print the value, you eval()

Here is the code you want:

import tensorflow as tf
from keras import backend as K

x= K.abs(-2.0)
with tf.Session() as sess:
    init = tf.global_variables_initializer()
    sess.run(init)
    print(x.eval())

The initializer is important to actually initialize x.

1

To print a tensor in TF 2.0 and above

my_sample = tf.constant([[3,5,2,6], [2,8,3,1], [7,2,8,3]])
  1. With session.run()
    with tf.compat.v1.Session() as ses: print(ses.run(my_sample))

  2. One line with eval()
    print(tf.keras.backend.eval(my_sample))

Anku5hk
  • 39
  • 3
0

For learning purpose, sometimes it is convenient to turn on the eager execution. With eager execution enabled, TensorFlow will execute operations immediately. You can then simply use the print or tensorflow.print() to print out the value of your object.

import tensorflow as tf
from keras import backend as K

tf.compat.v1.enable_eager_execution() # enable eager execution

x = K.abs(-2.0)
tf.Print(x,[x], 'x')

see here for more detail. https://www.tensorflow.org/api_docs/python/tf/compat/v1/enable_eager_execution

TimC
  • 305
  • 1
  • 3
  • 9