python - 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")
解决方案
推荐阅读
- javascript - 如何在完全加载之前获取图片元素的所选来源?
- hive - Hive 通过 hive.security.authorization.createtable.role.grants 撤销授权错误(基于 SQL 标准的 Hive 授权)
- asp.net - ParseXHtml 的“对象引用未设置为对象的实例”
- php - 如何更改 json 中的名称键或属性
- android - 如何使用单个查询更新所有行中的列 - Android Room Database
- javascript - 异步运行任务,并在完成后将类分配给 ReactJS 中的组件
- php - 在 Drupal 8 上包含 PHP 库
- java - Hibernate 中的事务管理
- awk - 如何使用列操作的 AWK printf 保持算术运算的精度
- python - 名称“文件”未定义错误 - 将 pdf 转换为文本