TensorFlow打印輸出tensor的值
在學習TensorFlow的過程中,我們需要知道某個tensor的值是什么,這個很重要,尤其是在debug的時候。也許你會說,這個很容易啊,直接print就可以了。其實不然,print只能打印輸出shape的信息,而要打印輸出tensor的值,需要借助class tf.Session, class tf.InteractiveSession。因為我們在建立graph的時候,只建立tensor的結構形狀信息,并沒有執(zhí)行數據的操作。
一 class tf.Session
運行tensorflow操作的類,其對象封裝了執(zhí)行操作對象和評估tensor數值的環(huán)境。這個我們之前介紹過,在定義好所有的數據結構和操作后,其最后運行。
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執(zhí)行相關操作,比如:Tensor.eval(), Operation.run()。Tensor.eval()是執(zhí)行這個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())
打印輸出張量的值的方法
import tensorflow as tf zeros = tf.zeros([3,3]) # 方法1 with tf.Session(): print(zeros.eval()) # 方法2 sess = tf.Session() print(sess.run(zeros))
打印輸出tensor變量的值的方法
import tensorflow as tf ones=tf.Variable(tf.ones([3,3])) # 方法1 InteractiveSession + initializer inter_sess=tf.InteractiveSession() ones.initializer.run() print(inter_sess.run(ones)) # 方法2 inter_sess=tf.InteractiveSession() tf.global_variables_initializer().run() print(inter_sess.run(ones)) # 方法3 Session + global_variables_initializer sess=tf.Session() sess.run(tf.global_variables_initializer()) print(sess.run(ones)) # 方法4 with Session + global_variables_initializer with tf.Session() as sess: sess.run(tf.global_variables_initializer()) print(sess.run(ones))
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
到此這篇關于TensorFlow打印輸出tensor的值的文章就介紹到這了,更多相關TensorFlow打印輸出tensor內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
Python如何優(yōu)雅刪除字符列表空字符及None元素
這篇文章主要介紹了Python如何優(yōu)雅刪除字符列表空字符及None元素,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友可以參考下2020-06-06

