我正在尝试编写自定义 Keras 损失函数,但在实现和调试代码时遇到问题。我的目标向量是:
y_pred = [p_conf, p_class_1, p_class_2]
其中,p_conf
= 检测到感兴趣事件的置信度
y_true
例子:
[0, 0, 0] = no event of interest
[1, 1, 0] = first class event
[1, 0, 1] = second class event
我使用多标签分类(即在我的最后一层中使用 sigmoid 激活和 binary_crossentropy 损失函数)获得了相对较好的结果,但我想使用计算以下的自定义损失函数进行实验和改进我的结果:
- 当 y_true = [0, ..., ...] 时的 binary_crossentropy 损失
- 当 y_true = [1, ..., ...] 时的 categorical_crossentropy 损失
这是 YOLO 对象检测算法使用的简化损失函数。我尝试调整YOLO 损失函数的现有 Keras / TensorFlow 实现,但没有成功。
这是我当前的工作代码。它运行但产生不稳定的结果。即损失和准确性随着时间的推移而降低。任何帮助将不胜感激。
import tensorflow as tf
from keras import losses
def custom_loss(y_true, y_pred):
# Initialisation
mask_shape = tf.shape(y_true)[:0]
conf_mask = tf.zeros(mask_shape)
class_mask = tf.zeros(mask_shape)
# Labels
true_conf = y_true[..., 0]
true_class = tf.argmax(y_true[..., 1:], -1)
# Predictions
pred_conf = tf.sigmoid(y_pred[..., 0])
pred_class = y_pred[..., 1:]
# Masks for selecting rows based on confidence = {0, 1}
conf_mask = conf_mask + (1 - y_true[..., 0])
class_mask = y_true[..., 0]
nb_class = tf.reduce_sum(tf.to_float(class_mask > 0.0))
# Calculate loss
loss_conf = losses.binary_crossentropy(true_conf, pred_conf)
loss_class = tf.nn.sparse_softmax_cross_entropy_with_logits(labels=true_class, logits=pred_class)
loss_class = tf.reduce_sum(loss_class * class_mask) / nb_class
loss = loss_conf + loss_class
return loss