您可以根据变量的性质实现损失函数。下面给出了一些标准的:
如果它们只是数字(而不是概率):
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
不仅限于这些。你可以创建自己的损失函数,只要它是可微的。