分类交叉熵在keras中是如何实现的?

2024-05-18 23:26:29 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图应用蒸馏的概念,基本上是为了训练一个新的更小的网络,使之与原来的网络一样,但计算量更少。

我有每个样本的softmax输出,而不是logits。

我的问题是,范畴交叉熵损失函数是如何实现的? 就像它取原始标签的最大值,并将其与同一索引中对应的预测值相乘,或者它对所有的logits(一个热编码)进行求和,如公式所示:

enter image description here


Tags: 函数网络概念编码标签交叉公式样本
2条回答

作为对“你知道epsilon和tf.clip_by_value在做什么吗?”,
它确保output != 0,因为tf.log(0)返回零除错误。
(我没有什么要评论的,但我想我会有所贡献)

我看到您使用了tensorflow标记,所以我猜这是您使用的后端?

def categorical_crossentropy(output, target, from_logits=False):
"""Categorical crossentropy between an output tensor and a target tensor.
# Arguments
    output: A tensor resulting from a softmax
        (unless `from_logits` is True, in which
        case `output` is expected to be the logits).
    target: A tensor of the same shape as `output`.
    from_logits: Boolean, whether `output` is the
        result of a softmax, or is a tensor of logits.
# Returns
    Output tensor.

这段代码来自keras source code。直接看代码应该能回答你所有的问题:)如果你需要更多的信息就直接问!

编辑:

以下是您感兴趣的代码:

 # Note: tf.nn.softmax_cross_entropy_with_logits
# expects logits, Keras expects probabilities.
if not from_logits:
    # scale preds so that the class probas of each sample sum to 1
    output /= tf.reduce_sum(output,
                            reduction_indices=len(output.get_shape()) - 1,
                            keep_dims=True)
    # manual computation of crossentropy
    epsilon = _to_tensor(_EPSILON, output.dtype.base_dtype)
    output = tf.clip_by_value(output, epsilon, 1. - epsilon)
    return - tf.reduce_sum(target * tf.log(output),
                          reduction_indices=len(output.get_shape()) - 1)

如果你看回报,他们会总结。。。:)

相关问题 更多 >

    热门问题