我正在尝试在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
能够工作;本质上,我们使用一个技巧来选择奇数和偶数索引;我们只乘以y_true
和y_pred
的对应部分,并考虑它们的奇偶性。
然后我们使用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