2017-10-06 142 views
0

我在添加对binary_crossentropy的惩罚时遇到了问题。当预定义的错误组的平均值违反某个阈值时,这个想法是惩罚损失函数。 以下是帮助函数,它用掩码表示组和已计算的crossentropy。它会简单地返回违反某个阈值的次数来惩罚调用它的实际损失函数。Keras中的自定义丢失函数的问题

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不是标量,我找不出一个简单的方法来比较它的阈值。

+0

我真的'不明白你想在这一行中实现什么:'error_mean = K.mean(errors [(groups_mask == group).nonzero()],axis = -1)' –

回答

2

必须使用张量和功能从keras backend

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. 
+0

我认为theano允许你不使用'cast '。 –

相关问题