http://blog.csdn.net/helei001/article/details/51750910
在學習TensorFlow的過程中,我們需要知道某個tensor的值是什么,這個很重要,尤其是在debug的時候。也許你會說,這個很容易啊,直接print就可以了。其實不然,print只能打印輸出shape的信息,而要打印輸出tensor的值,需要借助class tf.Session, class tf.InteractiveSession。因為我們在建立graph的時候,只建立tensor的結構形狀信息,並沒有執行數據的操作。
一 class tf.Session
運行tensorflow操作的類,其對象封裝了執行操作對象和評估tensor數值的環境。這個我們之前介紹過,在定義好所有的數據結構和操作后,其最后運行。
- import tensorflow as tf
- # Build a graph.
- a = tf.constant(5.0)
- b = tf.constant(6.0)
- c = a * b
- # Launch the graph in a session.
- sess = tf.Session()
- # Evaluate the tensor `c`.
- print(sess.run(c))
二 class tf.InteractiveSession
顧名思義,用於交互上下文的session,便於輸出tensor的數值。與上一個Session相比,其有默認的session執行相關操作,比如:Tensor.eval(), Operation.run()。Tensor.eval()是執行這個tensor之前的所有操作,Operation.run()也同理。
- import tensorflow as tf
- a = tf.constant(5.0)
- b = tf.constant(6.0)
- c = a * b
- with tf.Session():
- # We can also use 'c.eval()' here.
- print(c.eval())
Reference:
[1] https://www.tensorflow.org/versions/r0.9/api_docs/python/client.html#InteractiveSession
[2] http://stackoverflow.com/questions/33633370/how-to-print-the-value-of-a-tensor-object-in-tensorflow