You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

自定义Categorical_Crossentropy损失与内置版本性能不一致如何修正?

问题原因与解决方法
  • 你的自定义损失函数误用了tf.keras.metrics.categorical_crossentropy,而TensorFlow内置的categorical_crossentropy损失对应的是tf.keras.losses.categorical_crossentropy。二者设计目标不同:metrics版本用于计算评估指标,losses版本专门为训练优化做了数值稳定性等适配,直接混用会导致模型性能出现差异。

  • 修改后的自定义损失函数代码:

def CustomLoss(y_true, y_pred):
    usual_loss = tf.keras.losses.categorical_crossentropy(y_true, y_pred, from_logits=False, label_smoothing=0.0, axis=-1)
    return usual_loss

model.compile(
  loss=CustomLoss,
  optimizer='adam',
  metrics=['categorical_accuracy']
)
  • 若你只是想封装内置损失函数以便后续扩展,也可以直接使用CategoricalCrossentropy类实例,这更符合Keras的损失函数规范:
custom_loss = tf.keras.losses.CategoricalCrossentropy(from_logits=False, label_smoothing=0.0)

model.compile(
  loss=custom_loss,
  optimizer='adam',
  metrics=['categorical_accuracy']
)

内容的提问来源于stack exchange,提问作者Abdul Moid

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.10 11:36:02