How to print the value of a Tensor object in TensorFlow?
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:
In TensorFlow 2.x, thanks to eager execution, you can directly print the tensor value with .numpy()
:
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()
.
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.
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:
Here's your secret weapon to crack the vault:
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):
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.
Was this article helpful?