Python 如何使用多个变量作为Keras中一个输出的模型的损失?
我有一个Keras模型,它只有一个输出,但是为了计算自定义损失,我想用两个变量比较模型的输出。但问题是,如果我希望y_true的形状为?,2y_pred的形状也为?,2,而它应该是?,1。我可以将其中一个变量作为附加输入传递给模型,并在计算损失时使用输入层,但是这个变量实际上应该是未知的,因为它必须由模型预测。为了让目的更清楚,这里有一个类似于我想做的事情的例子: def有损校正1、有损校正2、有损校正前: 返回K.meansk.squarey_pred-y_true1+K.squarey_pred-y_true2,-1Python 如何使用多个变量作为Keras中一个输出的模型的损失?,python,python-3.x,tensorflow,keras,loss-function,Python,Python 3.x,Tensorflow,Keras,Loss Function,我有一个Keras模型,它只有一个输出,但是为了计算自定义损失,我想用两个变量比较模型的输出。但问题是,如果我希望y_true的形状为?,2y_pred的形状也为?,2,而它应该是?,1。我可以将其中一个变量作为附加输入传递给模型,并在计算损失时使用输入层,但是这个变量实际上应该是未知的,因为它必须由模型预测。为了让目的更清楚,这里有一个类似于我想做的事情的例子: def有损校正1、有损校正2、有损校正前: 返回K.meansk.squarey_pred-y_true1+K.squarey_pr
你可以有不同的形状与自定义损失,没有问题。你只需要有一致的结果 一些选择
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)
你可以有不同的形状与自定义损失,没有问题。你只需要有一致的结果 一些选择
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)