首页 > 解决方案 > Keras - 具有多个输出和每个输出不同权重的自定义损失函数

问题描述

我正在尝试在以下代码中训练具有多个输出的网络:X、Y logits 的损失在损失函数中的权重相同。我希望 X 的权重是 Y 的两倍。我在编译模型时尝试了损失权重,但似乎没有任何改变。

注意:我是 keras 和深度学习的新手

def custom_loss_fn(labels, model_outputs):

# target
    a_target = labels['a_target']
    b_target = labels['b_target']

#predictions x,y

    x_logits, y_logits = model_outputs

# Here I apply sparse_categorical cross-entropy function for the outputs 

    x_loss = tf.keras.backend.sparse_categorical_crossentropy(
        a_target, x_logits, from_logits=True)

    y_loss = tf.keras.backend.sparse_categorical_crossentropy(
        b_target, y_logits, from_logits=True)

# Weights are equals for both outputs
    total_loss = (tf.reduce_mean(x_loss) + tf.reduce_mean(y_loss)) / 2

# when I tried to make x_loss Weighted twice  y_loss, performance degrades; did I do something wrong here? 
# total_loss = ((tf.reduce_mean(x_loss) * 2 ) + tf.reduce_mean(y_loss)) / 2

    return total_loss

train_loss = tf.keras.metrics.Mean(name="train_loss")

标签: pythonkerasloss-function

解决方案


推荐阅读