[英]Printing inside jupyter notebook custom loss function with Keras/TF
在Keras中,如果您在Jupyter筆記本中進行自定義丟失功能,則無法打印任何內容。 例如,如果您有:
def loss_func(true_label, NN_output):
true_cat = true_label[:,0]
pred_cat = NN_output[:,0]
indicator = NN_output[:,1]
print("Hi!")
custom_term = K.mean(K.abs(indicator))
return binary_crossentropy(true_cat, pred_cat) + custom_term
評估該功能時,不會打印任何內容。
作為一種解決方法,如果我要進行一些調試,我發現我可以在cost函數中寫入文件,如果我想打印諸如int或字符串之類的標准內容,這將很有用。
但是,嘗試將類似張量的indicator
寫到文件中會產生令人難以置信的有用輸出:
Tensor("loss_103/model_105_loss/Print:0", shape=(512,), dtype=float32)
我知道TF提供了一個tf.Print()
方法來打印張量的值,但我不了解Jupyter的作用。 其他答案表明tf.Print()
寫入std。 錯誤,這意味着嘗試
sys.stderr = open('test.txt', 'w')
理論上應該允許我從文件中獲取輸出,但是不幸的是這不起作用(至少在Jupyter中)。
是否有任何通用方法可以將張量表示為字符串? 人們通常如何繞過這個障礙來查看您的代碼的作用? 如果我想出的方法比尋找均值更重要,那么我想確切地查看計算步驟中正在發生的事情,以驗證其是否可以正常工作。
謝謝!
您可以執行以下代碼:
def loss_func(true_label, NN_output):
true_cat = true_label[:,0]
true_cat = tf.Print(true_cat, [true_cat], message="true_cat: ") # added line
pred_cat = NN_output[:,0]
pred_cat = tf.Print(pred_cat, [pred_cat], message="pred_cat: ") # added line
indicator = NN_output[:,1]
custom_term = K.mean(K.abs(indicator))
return binary_crossentropy(true_cat, pred_cat) + custom_term
基本上,我添加了兩行來打印true_cat和pred_cat的值。 要打印某些內容,必須在上述語句的tf圖中包含print語句。
但是,訣竅是它將在jupyter筆記本電腦控制台上打印,而您要在jupyter筆記本電腦控制台上而不是在ipython筆記本電腦本身上運行筆記本電腦 。
參考文獻:
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.