![](/img/trans.png)
[英]TensorFlow's Print or K.print_tensor are not printing intermediate tensors in loss function
[英]TensorFlow's Print is not printing
我試圖從強化學習算法中理解一些代碼。 為了做到這一點,我試圖打印張量的值。
我做了一段簡單的代碼來說明我的意思。
import tensorflow as tf
from keras import backend as K
x = K.abs(-2.0)
tf.Print(x,[x], 'x')
目標是打印值“2”(-2 的絕對值)。 但我只得到以下信息:
Using TensorFlow backend.
Process finished with exit code 0
什么都沒有,我怎么能像 print('...') 語句那樣打印值 '2' 呢?
如果您使用的是 Jupyter Notebook,那么tf.Print()
不兼容,並且會按照文檔中的描述將輸出打印到 Notebook 的服務器輸出
在 tensorflow 文檔中,以下是對 Tensor 的描述:
在編寫 TensorFlow 程序時,您操作和傳遞的主要對象是 tf.Tensor。 一個 tf.Tensor 對象代表一個部分定義的計算,最終會產生一個值。
因此,您必須使用tf.Session()
初始化它們以獲取它們的值。 要打印值,您eval()
這是你想要的代碼:
import tensorflow as tf
from keras import backend as K
x= K.abs(-2.0)
with tf.Session() as sess:
init = tf.global_variables_initializer()
sess.run(init)
print(x.eval())
初始化器對於實際初始化 x 很重要。
在 TF 2.0 及更高版本中打印張量
my_sample = tf.constant([[3,5,2,6], [2,8,3,1], [7,2,8,3]])
使用 session.run()
with tf.compat.v1.Session() as ses: print(ses.run(my_sample))
一行帶有 eval()
print(tf.keras.backend.eval(my_sample))
出於學習目的,有時可以方便地打開 Eager Execution。 啟用 Eager Execution 后,TensorFlow 將立即執行操作。 然后您可以簡單地使用 print 或 tensorflow.print() 打印出您的對象的值。
import tensorflow as tf
from keras import backend as K
tf.compat.v1.enable_eager_execution() # enable eager execution
x = K.abs(-2.0)
tf.Print(x,[x], 'x')
有關更多詳細信息,請參見此處。 https://www.tensorflow.org/api_docs/python/tf/compat/v1/enable_eager_execution
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.