如何在keras中实现categorical_crossentropy?

时间:2017-05-29 07:06:38

标签: python tensorflow keras softmax loss-function

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

我为每个样本提供softmax输出而不是logits。

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

enter image description here

1 个答案:

答案 0 :(得分:5)

我看到你使用了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)

如果看一下回报,他们总结一下......:)