Explain Codes LogoExplain Codes Logo

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

python
eager-execution
tensorflow
tensor
Anton ShumikhinbyAnton Shumikhin·Feb 20, 2025
TLDR

To quickly inspect a Tensor in TensorFlow you typically want to evaluate it within a session. Use the eval() function in a tf.compat.v1.Session() in TensorFlow 1.x:

import tensorflow as tf # Define the tensor. a_tensor = tf.constant([1, 2, 3]) # Evaluate and print the value. with tf.compat.v1.Session() as sess: print(a_tensor.eval()) # Display the magic (and also the value of a_tensor).

In TensorFlow 2.x, thanks to eager execution, you can directly print the tensor value with .numpy():

a_tensor = tf.constant([1, 2, 3]) print(a_tensor.numpy()) # Poof! Tensor has been ninja-converted into a numpy array.

A dive into Eager and compatibility mode

TensorFlow 2.x made eager execution the default, leading to immediate evaluation akin to typical Pythonic data structures. However, in TensorFlow 1.x, you can also enjoy eager execution. Just let TensorFlow know your desire by explicitly enabling it using tf.enable_eager_execution().

tf.enable_eager_execution() # More fun! Less hassle!

Use tf.print() for outputting directly to your cell in Jupyter notebooks or Colab instead of the console log. It's like the VIP pass for your output.

Interactive session essentials

Interactive sessions come in handy when developing or testing your ideas in a more dynamic way. These sessions offer an interactive environment, freeing you from the typical verbosity of TensorFlow sessions.

interactive_sess = tf.compat.v1.InteractiveSession() # It's party time! a_tensor = tf.constant([1, 2, 3]) print(a_tensor.eval()) # What's in the box? interactive_sess.close() # Party's over.

Remember to close your party place, ahem, InteractiveSession when you're done to keep things tidy.

Exploring your Tensor

Now, to intimately explore your tensor:

Think of a **criminal mastermind** sitting in a **vault**. Now imagine, that mastermind is your **Tensor object** and the vault is the Tensor's value. **Invisible to the naked eye**. Seriously, try.

Here's your secret weapon to crack the vault:

print(a_tensor.numpy()) # Ta-da! We're in.
Before: (🕴️) <-- A seemingly chill Tensor object After: ($$) <-- Jackpot! That's your value.

Note: .numpy() only works when eager execution is enabled.

Taming non-constant tensors

When dealing with tensors that aren't constants (like tensors depending on variables inputs), tf.get_static_value() is your best friend. It quickly identifies if a tensor's value is constant. No unnecessary graph execution needed - an equivalent to seeing through walls (if those walls were TensorFlow operations):

maybe_constant_tensor = tf.get_static_value(tensor) if maybe_constant_tensor is not None: print(maybe_constant_tensor) else: print("This tensor is as constant as a chameleon.")

Dealing with legacy artifacts

Be extra cautious of deprecated operations, such as tf.Print(). They are like power ballads of the 80s; nostalgic but not appropriate in all contexts. Instead, use tf.print() to monitor your computations in TensorFlow 2.x. In the same vein, tf.initialize_all_variables() is replaced by tf.global_variables_initializer().

Insight into the life of a Tensor

Note that a tensor spills the beans about its properties, like dimensions and the operations they represent, before execution. This comes handy for setting up control dependencies, especially when performing selective calculations.

Unveiling the magic

When working with tensors spitting out random values, TensorFlow 1.x requires you to whisper the magic words Session.run(). However, TensorFlow 2.x is a mellowed-out wizard that doesn't require the chanting thanks to eager execution.

random_tensor = tf.random.normal([3]) print(random_tensor.numpy()) # Who needs Hogwarts when you have TensorFlow?