![](/img/trans.png)
[英]design a custom loss function in Keras (on the element index in tensors in Keras)
[英]Writing a custom loss function element by element for Keras
我是機器學習,python和tensorflow的新手。 我習慣用C ++或C#編寫代碼,我很難使用tf.backend。 我正在嘗試為LSTM網絡編寫自定義丟失函數,該網絡試圖預測時間序列的下一個元素是正還是負。 我的代碼與binary_crossentropy損失函數運行良好。 我現在想改進我的網絡有一個損失函數,如果預測概率大於0.5,則增加下一個時間序列元素的值,如果概率小於或等於0.5,則減去它。 我試過這樣的事情:
def customLossFunction(y_true, y_pred):
temp = 0.0
for i in range(0, len(y_true)):
if(y_pred[i] > 0):
temp += y_true[i]
else:
temp -= y_true[i]
return temp
顯然,尺寸是錯誤的,但由於我在調試時無法進入我的功能,因此很難掌握尺寸。 如果我可以使用逐個元素的功能,你能告訴我嗎? 如果有,怎么樣? 如果沒有,你能用tf.backend幫助我嗎? 非常感謝
從keras后端函數,您可以使用greater
的函數:
import keras.backend as K
def customLossFunction(yTrue,yPred)
greater = K.greater(yPred,0.5)
greater = K.cast(greater,K.floatx()) #has zeros and ones
multiply = (2*greater) - 1 #has -1 and 1
modifiedTrue = multiply * yTrue
#here, it's important to know which dimension you want to sum
return K.sum(modifiedTrue, axis=?)
應根據要求的總和使用axis
參數。
axis=0 -> batch or sample dimension (number of sequences)
axis=1 -> time steps dimension (if you're using return_sequences = True until the end)
axis=2 -> predictions for each step
現在,如果您只有2D目標:
axis=0 -> batch or sample dimension (number of sequences)
axis=1 -> predictions for each sequence
如果您只想對每個序列求和,那么就不要放軸參數。
由於它僅包含來自yTrue
值,因此無法反向傳播以更改權重。 這將導致“無值不支持”錯誤或類似的東西。
雖然yPred
(連接到模型權重的那個)在函數中使用,但它僅用於獲得真正的x false條件,這是不可微分的。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.