[英]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.