将Keras中的损失函数定义为逐元素乘法,每二个元素取一个否定



我正试图在运行于Tensorflow之上的Keras中定义我自己的成本函数。虽然y_true = [a0, a1, a2, a3, ..., an]y_pred = [b0, b1, b2, b3, ..., bn]分别作为基本事实和预测,但我想将成本函数定义为:cost = a0*b0 - a1*b1 + a2*b2 - a3*b3 + ...

简而言之,我想定义如下:

def my_cost(y_true, y_pred):
return tf.math.multiply(y_true, y_pred)

但是每一秒的元素都必须被否定。你有什么想法吗?

我希望以下cost_function能够工作;从本质上讲,我们做了一个技巧,选择奇数和偶数索引;考虑到CCD_ 5和CCD_。

然后我们使用tf.math.reduce_sum()来实际计算成本的总和;您也可以使用tf.math.subtract(first_sum,second_sum),但为了简单起见,我保留了"-"。

def my_cost(y_true, y_pred):
y_true_even = y_true[::2]
y_true_odd = y_true[1::2]
y_pred_even = y_pred[::2]
y_pred_odd = y_pred[1::2]
result = tf.math.reduce_sum(tf.math.multiply(y_true_even,y_pred_even)) - tf.math.reduce_sum(tf.math.multiply(y_true_odd,y_pred_odd)) 
return result

相关内容

最新更新