tensorflow Fetch the value of a TensorFlow variable or a Tensor


Example

Sometimes we need to fetch and print the value of a TensorFlow variable to guarantee our program is correct.

For example, if we have the following program:

import tensorflow as tf
import numpy as np
a = tf.Variable(tf.random_normal([2,3])) # declare a tensorflow variable
b = tf.random_normal([2,2]) #declare a tensorflow tensor
init = tf.initialize_all_variables()

if we want to get the value of a or b, the following procedures can be used:

with tf.Session() as sess:
    sess.run(init)
    a_value = sess.run(a)
    b_value = sess.run(b)
    print a_value
    print b_value

or

with tf.Session() as sess:
    sess.run(init)
    a_value = a.eval()
    b_value = b.eval()
    print a_value
    print b_value