[英]Trouble with custom loss function in Keras
我在對binary_crossentropy添加懲罰時遇到了麻煩。 想法是當預定義的錯誤組的平均值超過某個閾值時,對損失函數進行懲罰。 下面是使用掩碼表示組和已經計算出的交叉熵的輔助函數。 它只會返回違反某個閾值的次數,以懲罰調用它的實際損失函數。
def penalty(groups_mask, binary_crossentropy):
errors = binary_crossentropy
unique_groups = set(groups_mask)
groups_mask = np.array(groups_mask)
threshold = # whatever
c = 0
for group in unique_groups:
error_mean = K.mean(errors[(groups_mask == group).nonzero()], axis=-1)
if error_mean > threshold:
c += 1
return c
問題在於error_mean不是標量,我無法弄清將其與閾值進行比較的簡單方法。
您必須使用keras 后端中的 張量和函數來完成所有操作
import keras.backend as K
在錯誤的那一行,您還必須使用這些函數比較事物:
....
c = K.variable([0])
.....
.....
errorGreater = K.cast(K.greater(error_mean,threshold), K.floatx())
c+=K.max(errorGreater) #if error_mean is 1 element only, you can just c+=errorGreater.
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.