學習TensorFlow,打印輸出tensor的值


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數值的環境。這個我們之前介紹過,在定義好所有的數據結構和操作后,其最后運行。

 

[python]  view plain  copy
 
  1. import tensorflow as tf  
  2.   
  3. # Build a graph.  
  4. a = tf.constant(5.0)  
  5. b = tf.constant(6.0)  
  6. c = a * b  
  7. # Launch the graph in a session.  
  8. sess = tf.Session()  
  9. # Evaluate the tensor `c`.  
  10. print(sess.run(c))  
 
        

 

二 class tf.InteractiveSession

顧名思義,用於交互上下文的session,便於輸出tensor的數值。與上一個Session相比,其有默認的session執行相關操作,比如:Tensor.eval(), Operation.run()。Tensor.eval()是執行這個tensor之前的所有操作,Operation.run()也同理。

 

[python]  view plain  copy
 
  1. import tensorflow as tf  
  2. a = tf.constant(5.0)  
  3. b = tf.constant(6.0)  
  4. c = a * b  
  5. with tf.Session():  
  6.   # We can also use 'c.eval()' here.  
  7.   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

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM