【问题标题】:What is the syntax for passing arguments into keras loss functions?将参数传递给 keras 损失函数的语法是什么?
【发布时间】:2020-05-20 19:20:15
【问题描述】:

我正在尝试使用 from_logits=True 给我的 keras 神经网络分类交叉熵损失。但是,我不确定如何将其传递到代码中,因为它要求我指定目标和输出。

通常我可以使用:

network.compile(sgd, loss='categorical_crossentropy'),

但现在我不得不试试这个:

network.compile(sgd, loss=categorical_crossentropy(from_logits=True))

这给了我一个错误:

TypeError: categorical_crossentropy() missing 2 required positional arguments: 'target' and 'output'

我能想到的最好的是:

network.compile(sgd, loss=categorical_crossentropy(y_true, network.output, from_logits=True))

我不知道应该为 y_true 放置什么,因为这不是网络的一部分。我在网上浏览了一下,但没有遇到任何指定如何执行此操作的内容,包括奇怪的 keras 文档。

【问题讨论】:

  • 你试过了吗,tf.keras.losses.CategoricalCrossentropy(from_logits=True)

标签: keras syntax


【解决方案1】:

Keras 损失严格地需要两个参数:y_true(地面实况数据)和y_pred(模型的输出)。

如果要使用具有不同签名的函数,则必须将其包装以遵循正确的签名。

import keras.backend as K

def cc_from_logits(y_true, y_pred):
    return K.categorical_crossentropy(y_true, y_pred, from_logits=True, axis=-1)

model.compile(loss=cc_from_logits)

我非常相信cc_with_logits 带来的结果与softmax + 'categorical_crossentropy' 完全相同。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-05-29
    • 2016-06-07
    • 2022-12-05
    • 2023-01-12
    • 1970-01-01
    • 2020-12-03
    相关资源
    最近更新 更多