How to Get the Current Value of a Variable in TensorFlow?

Problem Formulation

Given a TensorFlow variable created with tf.Variable(). As this variable may have changed during the training process (e.g., using assign()), you want to get the current value of it. How to accomplish this in TensorFlow?

x = tf.Variable(...)
# What's the current value?

Sessions Are Gone in TensorFlow 2

In TensorFlow 1, computations were performed within Sessions. That’s why many people proposed to solve this problem in TensorFlow 1 via the Session().run(x) call. For example, look at this code from here:

# OLD: WORKS ONLY IN TENSORFLOW 1!!!
import tensorflow as tf

x = tf.Variable([42.0, 21.0])
init = tf.global_variables_initializer()

with tf.Session() as sess:
    sess.run(init)
    your_var = sess.run(x)
    print(your_var)

However, the new API of the TensorFlow 2 framework has largely removed the need to explicitly run computations in sessions:

Sessions are gone in TensorFlow 2. There is one global runtime in the background that executes all computation, whether run eagerly or as a compiled tf.function.” — source

Get Current Value of Variable in TensorFlow 2

To get the current value of a variable x in TensorFlow 2, you can simply print it with print(x). This prints a representation of the tf.Variable object that also shows you its current value. If you want a clean representation of a tf.Variable stored in variable x, try x.numpy().

Here’s an example that showcases both variants:

import tensorflow as tf
x = tf.Variable(42)
print(x)
print(x.numpy())

The output of this code snippet is:

<tf.Variable 'Variable:0' shape=() dtype=int32, numpy=42>
42

You can try it yourself in the interactive Jupyter Notebook here:

How to Get the Current Value of a Variable in TensorFlow?
Click to run interactive notebook in your browser.

Where to Go From Here

TensorFlow is an exciting framework! ? We’ve compiled a number of TensorFlow cheat sheets in our article here. Check them out!

If you love cheat sheets, join our Python email academy with 11+ free cheat sheets for you to download!

You can also join the Finxter Email Acadamy with tens of thousands of ambitious coders here: