多个输出的单损耗

问题描述 投票:0回答:1

我想在Keras / Tensorflow中创建一个具有多个输出的神经网络。我想创建一个将所有输出都考虑在内的SINGLE损失函数,并据此计算损失。我需要这样做,因为输出彼此相关。我该如何实现?我读到有关将所有输出串联到单个密集层,然后计算该层的损耗的信息。是否有一种更方便的方法来实现多输出的单一损失?

我在想类似的东西:

def my_custom_loss(y_true_0, ..., y_true_n, y_pred_0, ..., y_pred_n):
   return something

[y_true_0, ..., y_true_ny_pred_0, ..., y_pred_n

应该是n个输出(密集)层的真实/预测输出。

python tensorflow keras loss
1个回答
0
投票

您可以根据变量的性质实现损失函数。下面给出一些标准的:

如果它们只是数字(而不是概率):MSE损失

def my_custom_loss(y_true_0, ..., y_true_n, y_pred_0, ..., y_true_n):
   y_true = tf.stack([y_true_0,...y_true_n], axis=0)
   y_pred = tf.stack([y_pred_0,...y_pred_n], axis=0)
   something = tf.losses.mean_squared_error(y_true, y_pred)
   return something

OR绝对差损失

def my_custom_loss(y_true_0, ..., y_true_n, y_pred_0, ..., y_true_n):
   y_true = tf.stack([y_true_0,...y_true_n], axis=0)
   y_pred = tf.stack([y_pred_0,...y_pred_n], axis=0)
   something = tf.losses.absolute_difference(y_true, y_pred)
   return something

如果它们是一个热门向量(有效概率):

def my_custom_loss(y_true_0, ..., y_true_n, y_pred_0, ..., y_true_n):
   y_true = tf.stack([y_true_0,...y_true_n], axis=0)
   y_pred = tf.stack([y_pred_0,...y_pred_n], axis=0)
   something = tf.reduce_mean(tf.keras.losses.binary_crossentropy(y_true, y_pred))
   return something

如果它们是零和一(无效概率):

def my_custom_loss(y_true_0, ..., y_true_n, y_pred_0, ..., y_true_n):
   y_true = tf.stack([y_true_0,...y_true_n], axis=0)
   y_pred = tf.stack([y_pred_0,...y_pred_n], axis=0)
   something = tf.reduce_mean(tf.keras.losses.binary_crossentropy(y_true, y_pred), from_logits=True)
   return something

不仅限于这些。您可以创建自己的损失函数,只要它是可微的。

© www.soinside.com 2019 - 2024. All rights reserved.