【问题标题】:Keras custom loss function - shape mismatch despite returning same shape as categorical crossentropyKeras 自定义损失函数 - 尽管返回与分类交叉熵相同的形状,但形状不匹配
【发布时间】:2021-07-23 20:18:00
【问题描述】:

我创建了一个基于余弦的自定义损失函数:

def cos_loss(y_true, y_pred):
    norm_pred = tf.math.l2_normalize(y_pred)
    dprod = tf.tensordot(
        a=y_true,
        b=norm_pred,
        axes=1
    )
    return 1 - dprod

但是,使用此自定义损失训练模型会导致错误 In[0] mismatch In[1] shape: 2 vs. 8: [8,2] [8,2] 0 0。如果我使用分类交叉熵之类的内置损失函数,则模型可以毫无问题地进行训练。

尽管我的自定义损失和分类交叉熵返回值的类型和形状完全相同。例如,我创建了测试 y_truey_pred 并运行它们:

test_true = np.asarray([1.0, 0.0])
test_pred = np.asarray([0.9, 0.2])
print(cos_loss(test_true, test_pred))
print(tf.keras.losses.categorical_crossentropy(test_true, test_pred))

返回:

> tf.Tensor(0.023812939816047263, shape=(), dtype=float64)
  tf.Tensor(0.20067069546215124, shape=(), dtype=float64)

因此,两者都给出了具有单个 float-64 值且没有形状的 TF 张量。那么,如果形状输出相同,为什么我会在一个上出现形状不匹配错误,而在另一个上却没有呢?谢谢。

【问题讨论】:

    标签: python tensorflow machine-learning keras loss-function


    【解决方案1】:

    您的损失函数应该能够接收一批预测和基本事实并返回一批损失值。目前,情况并非如此,因为 tensordotaxis=1 是矩阵乘法,当您开始引入批量维度时,您会遇到维度冲突。

    您或许可以改用以下内容:

    def cos_loss(y_true, y_pred):
        norm_pred = tf.math.l2_normalize(y_pred)
        dprod = tf.reduce_sum(y_true*norm_pred, axis=-1)
        return 1 - dprod
    

    【讨论】:

      猜你喜欢
      • 2017-12-16
      • 2017-06-26
      • 1970-01-01
      • 2019-07-28
      • 2017-12-08
      • 1970-01-01
      • 2020-08-09
      • 2019-07-13
      • 1970-01-01
      相关资源
      最近更新 更多