如何在 Keras 中使用多个变量作为具有一个输出的模型的损失?

How to use multiple variables as loss for a model with one output in Keras?

我有一个只有一个输出的 Keras 模型,但为了计算自定义损失,我想将模型的输出与两个变量进行比较。但问题是,如果我希望 y_true 具有 (?, 2) 的形状,y_pred 也会具有 (?, 2) 的形状,而它应该是 (?, 1)。我可以将其中一个变量作为附加输入传递给模型,并在计算损失时使用输入层,但实际上这个变量应该是未知的,因为它必须由模型预测。为了使目的更清楚,这里有一个类似于我想做的事情的例子:

def loss(y_true1, y_true2, y_pred):
    return K.mean(K.square(y_pred-y_true1) + K.square(y_pred-y_true2), -1)

你可以有不同的形状和自定义损失,没问题。你只需要有一致的结果。

几个选项

def loss(y_true, y_pred): #where true is shape (batch, 2) and pred is shape (batch, 1)
    return K.mean(K.square(y_true - y_pred), axis=-1)

def loss(y_true, y_pred): #where true is shape (batch, 2) and pred is shape (batch,)
    return K.square(y_pred - y_true[:,0]) + K.square(y_pred - y_true[:,1])

def loss(y_true, y_pred): #where true is shape (batch, 2) and pred is shape (batch,)
    y_pred = K.reshape(y_pred, (-1,1))
    return K.mean(K.square(y_true - y_pred), axis=-1)