首页 文章

Tensorflow / Keras自定义丢失功能

提问于
浏览
0

我想在keras中创建自定义丢失函数 .

假设我有yTrue和yPred,它们是真实和预测标签的张量(n×m) .

让我们调用每个样本n(即yTrue和yPred中的每一行)yT和yP . 然后我想要一个在yT [0] == 1时计算(yT-yP)^ 2的损失函数,否则它将计算(yT [0] -yP [0])^ 2 .

That is: for each sample I always want to calculate the squared error for the first element - but I want to calculate the squared error of the other elements only if the first element of the true label == 1.

如何在自定义丢失功能中执行此操作?

这是我到目前为止所获得的:

我需要通过张量操作来做到这一点 . 首先,我可以计算

Y = (yTrue - yPred)^2

然后我可以定义一个屏蔽矩阵,其中第一列始终为1,其他列为1,具体取决于yTrue每行的第一个元素的值 . 所以我可以得到类似的东西

1 0 0 0 0 
1 0 0 0 0
1 1 1 1 1
1 1 1 1 1 
1 0 0 0 0

然后,我可以将这个矩阵元素乘以Y并获得我想要的东西 .

但是,如何生成掩蔽矩阵?特别是,如何在tensorflow / keras中执行“如果行的第一个元素是1”的条件?

也许有更好的方法来做到这一点?谢谢

1 回答

  • 1

    您可以在后端使用条件开关 K.switch . 有点像:

    mse = K.mean(K.square(y_pred - y_true), axis=-1) # standard mse
    msep = K.square(y_pred[:,0] - y_true[:,0])
    return K.switch(K.equals(y_true[:,0], 1), mse, msep)
    

    编辑每个样品条件的处理 .

相关问题