獲取 TensorFlow 變數或 Tensor 的值

有時我們需要獲取並列印 TensorFlow 變數的值以保證我們的程式是正確的。

例如,如果我們有以下程式:

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()

如果我們想獲得 a 或 b 的值,可以使用以下過程:

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

要麼

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