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
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:
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:
While working as a researcher in distributed systems, Dr. Christian Mayer found his love for teaching computer science students.
To help students reach higher levels of Python success, he founded the programming education website Finxter.com. He’s author of the popular programming book Python One-Liners (NoStarch 2020), coauthor of the Coffee Break Python series of self-published books, computer science enthusiast, freelancer, and owner of one of the top 10 largest Python blogs worldwide.
His passions are writing, reading, and coding. But his greatest passion is to serve aspiring coders through Finxter and help them to boost their skills. You can join his free email academy here.