How to print the value of a Tensor object in TensorFlow?
The easiest[A] way to evaluate the actual value of a Tensor
object is to pass it to the Session.run()
method, or call Tensor.eval()
when you have a default session (i.e. in a with tf.Session():
block, or see below). In general[B], you cannot print the value of a tensor without running some code in a session.
If you are experimenting with the programming model, and want an easy way to evaluate tensors, the tf.InteractiveSession
lets you open a session at the start of your program, and then use that session for all Tensor.eval()
(and Operation.run()
) calls. This can be easier in an interactive setting, such as the shell or an IPython notebook, when it's tedious to pass around a Session
object everywhere. For example, the following works in a Jupyter notebook:
with tf.Session() as sess: print(product.eval())
This might seem silly for such a small expression, but one of the key ideas in Tensorflow 1.x is deferred execution: it's very cheap to build a large and complex expression, and when you want to evaluate it, the back-end (to which you connect with a Session
) is able to schedule its execution more efficiently (e.g. executing independent parts in parallel and using GPUs).
[A]: To print the value of a tensor without returning it to your Python program, you can use the tf.print()
operator, as Andrzej suggests in another answer. According to the official documentation:
To make sure the operator runs, users need to pass the produced op to
tf.compat.v1.Session
's run method, or to use the op as a control dependency for executed ops by specifying withtf.compat.v1.control_dependencies([print_op]
), which is printed to standard output.
Also note that:
In Jupyter notebooks and colabs,
tf.print
prints to the notebook cell outputs. It will not write to the notebook kernel's console logs.
[B]: You might be able to use the tf.get_static_value()
function to get the constant value of the given tensor if its value is efficiently calculable.
TF 2.0 print tensor values
Inside the graph indicated by the decorator @tf.function
, you can use tf.print to print the values of your tensor.
tf.print(new_x)
Here is how the code can be rewritten
class Data:
def __init__(self):
pass
def back_to_zero(self, input):
time = tf.slice(input, [0,0], [-1,1])
new_time = time - time[0][0]
return new_time
@tf.function
def load_data(self, inputs):
new_x = self.back_to_zero(inputs)
tf.print(new_x) # print inside the graph context
return new_x
time = np.linspace(0,10,20)
magntiudes = np.random.normal(0,1,size=20)
x = np.vstack([time, magntiudes]).T
d = Data()
data = d.load_data(x)
print(data) # print outside the graph context
the tensor type outside the tf.decorator
context is of type tensorflow.python.framework.ops.EagerTensor
. To convert it to a numpy array, you can use data.numpy()
How to get the value of a tensor? Python
It looks to me as if you have not evaluated the tensor. You can call tensor.eval()
to evaluate the result, or use session.run(tensor)
.
import tensorflow as tf
a = tf.constant(3.5)
b = tf.constant(4.5)
c = a * b
with tf.Session() as sess:
result = c.eval()
# Or use sess.run:
# result = sess.run(c)
print(result)
# out: 15.75
print(type(result))
# out: <class 'numpy.float32'>
Get the integer value inside a tensor tensorflow
You can use Tensor.numpy()
method to convert tensorflow.Tensor
to numpy
array or if you don't want to work with numpy
representation Tensor.numpy().tolist()
converts your variable to python list.
test = tf.constant([1,4,5])
np_array = test.numpy()
python_list = np_array.tolist()
integer_value = np_array[0] # or python_list[0]
EDIT:
if you turn off the eager execution you are left off with TF 1.0 behaviour so you have to make a tensorflow.Session
to evaluate any tensorflow.Tensor
tf.compat.v1.disable_eager_execution()
test = tf.constant([4, 5, 6])
sess = tf.compat.v1.Session()
sess.run(tf.compat.v1.global_variables_initializer())
np_array = test.eval(session=sess))
Related Topics
How to Filter Only Printable Characters in a File on Bash (Linux) or Python
Multi Platform Portable Python
Running a Bash Script from Python
Executable Python Program with All Dependencies for Linux
Checking Running Python Script Within the Python Script
I Have a Problem with Sending Mail:Typeerror: _Init_() Got an Unexpected Keyword Argument 'Context'
Use Df Command to Show Only the %Used
How to Run Celery Workers by Superuser
Change Parent Shell's Environment from a Subprocess
Creating a Symbolic in Shared Volume of Docker and Accessing It in Host MAChine
How to Install Writable Shared and User Specific Data Files with Setuptools
How to Send Http Requests to Flask Server