8

我正在尝试应用蒸馏的概念,基本上是为了训练一个新的更小的网络来做与原始网络相同但计算量更少的网络。

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

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

在此处输入图像描述

4

2 回答 2

8

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

于 2019-03-12T02:16:05.587 回答
7

我看到您使用了 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 源代码。直接查看代码应该可以回答您所有的问题 :) 如果您需要更多信息,请询问!

编辑 :

这是您感兴趣的代码:

 # 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)

如果您查看回报,他们会总结... :)

于 2017-05-29T19:55:14.793 回答